Use PHP to send an Email

by Kim Joy Fox | November 21, 2012 | Programmers | Tags: , , ,

phpemailSending an email through PHP is surprisingly simple and straightforward. Just remember a few simple requirements, and watch the apostrophes.

Here’s the code in entirety:

$message = "Hi !

This is my email message and a link: <a href="">KimJoyFox</a>

Visit Kim Joy Fox for tutorials, information, etc.



$to = $email;

$headers = 'MIME-Version: 1.0' . "rn";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
$headers .= 'From: Website<>' . "rn";

$subject = "Hello World!";
$body = $message;
$email_from = "";
ini_set("sendmail_from", $email_from);
mail($to, $subject, $body, $headers);

The Message Variable

We’ll start with setting up the message part of the email. There are multiple ways of doing this, but we’ll use a very simple string variable – text with a bit of HTML.

Whether you use double quotes or single quotes, make sure you close each section correctly. For our message, we included some line breaks

and a link, with the URL in single quotes (since the string is in double quotes).

The To Variable

This is the email we’ll be sending the email to.

The Headers Variable

There are three requirements within the headers. The first is the MIME-Version information. Second, is the “Content-Type” information, and lastly, the “From” information. After we initially set the Header variable, in Line 5, we add to it (using the .=) to add to the variable. Separating them just makes it easier to work with.

Final Variables

We’ll finish up with the subject, body, email_from variables. The Subject is obviously the ¬†subject of the email. The Body variable is set to the Message variable we defined in Line 1. We don’t really need to set this again, it just keeps it all together.

Finally, we’ll set the email_from variable to the email that will be the “Sent From” Email.


This is the kicker. If your PHP emails aren’t working, here’s what you’re missing. Some servers need the “ini_set” to be set before the email is sent. If everything else is correct and the email isn’t going through, then set “ini_set” and try again.

Send the Email

In the last line, 13, we’ll use the built-in PHP mail function, and include all the variables we just set.


Designing Programming Business

Leave a Reply

Your email address will not be published.




Include all code within < code > tags.
You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>