Ben Griffiths - Freelance PHP Web Developer
Ben Griffiths - Freelance PHP Developer

Sending Email with PHP

01
Jun

One of the more common tasks you'll perform with PHP will be sending out emails. These can be from contact forms, user registrations etc. There are two types of email that you will probably be sending, Plain Text, and HTML.

Sending PHP Plain Text Email

Sending plain text emails is actually really simple, to do so we use the 'mail' function thats built right into PHP. Take a look at the following:

<?

$message 
'Hi,\n\nthis is a message!';  // The \n denotes a new line

mail('me@mydomain.com''My Emails Subject'$message);

?>

Executing that bit of code will send an email to the address 'me@mydomain.com', with the subject line 'My Emails Subject'. The body of the email is the contents of '$message'. Thats all there is to sending plain text PHP emails!

Sending PHP HTML Email

To send a HTML email, we still use the 'mail' function, but we need to add some more data. What we add are called headers, and this is what email programs use to tell what kind of email they are reading. Take a look at the folling example:

<?

$message 
'Hi,<br />this is a <strong>message!</strong>';  // We can now embed HTML!

$headers  'MIME-Version: 1.0'.'\r\n';
$headers .= 'Content-type: text/html; charset=iso-8859-1'.'\r\n';

mail('me@mydomain.com''My Emails Subject'$message$headers);

?>

As you can see, we have two new lines called headers, the mime type and content type. These ensure that the email program used when reading the email knows that this email contains HTML and renders it correctly. We can now also embed HTML within the email's body text too.

Known Issues with Sending PHP Emails

There are some issues with using the 'mail' function within PHP, most notably that webmail providers will often mark this kind of mail as spam. This is because the sending address cannot always be verified or set up correctly. To this end, there are several third party PHP classes that can send email via a true SMTP server. My favourite is Swift Mailer.

Comments

Tom's Gravatar

Tom - June 3rd, 2008

I've found that using a library such as Swiftmailer can help reduce the chance of getting stopped as spam and improve delivery rates. So much better than trying to set all the required headers manually. Another option is phpmailer.

info@megasamit.com's Gravatar

info@megasamit.com - July 16th, 2008

Dear,

Please, i need more tutorial on sending mail with PHP, that is after the sender click the send button, you will be prompt with a message indicating the senders name and other details. Please, i need tutorials for such PHP email form.

Thank you.

Sam.

Leave a comment