Send Emails

Sending emails in PHP is extremely easy. Before we get to sending emails, let’s think about why we might want to send an email in the first place. A simple contact form obviously requires an email to be sent. After a user creates an account, we probably want to send them an email so they can confirm their email address. There are many other uses of sending emails, but I don’t want you using email for the wrong purposes. Sometimes, you will see emails being awkwardly used for data storage rather than be alerts or some type of communication. Ultimately, a database is clearly a better way to do data storage and emails are great for communication.

Sending an Email

Now that we know why we might want to send emails, let’s start sending some. You might notice that sending emails is disabled in the PHP Notepad. Well, that is so spammers don’t use to send their junk mail. Anyways, let’s see an example.

	mail('[email protected]','I am the Subject!','I am the message');

Like I said, sending emails is easy with the mail(). All you need to provide is what email address you are sending the email to, the subject, and the message.

Email Headers

Sometimes, we want to send more than just the subject and message to someone. Maybe we want to provide a return address or send an HTML email. Well, these extra parameters all go in the email header. First, let’s just try to setting the return address.

$headers = "From: \r\n"; 
$headers .= "Reply-To: [email protected] \r\n";
mail('[email protected]','I am the Subject!','I am the message',$headers);

So, all we did was to add another variable, $headers, to our mail function. The new variable joined two strings of text. First, we set who the email is from and then set the “Reply-To” to another email address. So, this email will say that it is from “”, but when you reply to the email, your response will go to “[email protected]”.

HTML Emails

Sending HTML emails in PHP is pretty simple as well. We need to add a few more lines to our $headers variable and edit our message. Let’s take a look at an example.

$headers = "From: \r\n"; 
$headers .= "Reply-To: [email protected] \r\n"; 
$headers .= "MIME-Version: 1.0 \r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1 \r\n";

$message = '<html><body><h1>After Hours Programming</h1></body></html>';
mail('[email protected]','I am the Subject!',$message,$headers);

After we set MIME type, Content Type, and the charset, PHP will just add these into the email header. Whenever an email service receives the email, it will check these parameters in the header and display the email as HTML. Don’t forget that you can use the style attribute to format your HTML email.

Leave a Comment

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