How to send an email in PHP

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:





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.