How to send an email in PHP

- by

Many complex things are extremely simple in PHP – sending mail is one of them. Here’s how:

// components for our email
$recepients = 'you@somewhere.com';
$subject = 'Hello from PHP';
$message = 'This is a test mail.';

// let's send it 
$success = mail($recepients, $subject, $message);
if ($success) {
	echo 'Mail added to outbox';
} else {
	echo 'That did not work so well';
}

The mail function will add the message to the out queue, so the test will not show if the message has actually been sent.

To avoid really long single line emails (i.e. entire message on one line) we can use the wordwrap() function, causing an automatic wrap to the next line if more than 70 characters are in a single row:

$message = wordwrap($message, 70, "\r\n"); 

All tips courtesy of the PHP Manual Pages:



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.