Use PHP to send an Email
Sending 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="http://kimjoyfox.com">KimJoyFox</a> Visit Kim Joy Fox for tutorials, information, etc. Sincerely, Me"; $to = $email; $headers = 'MIME-Version: 1.0' . "rn"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn"; $headers .= 'From: Website<firstname.lastname@example.org>' . "rn"; $subject = "Hello World!"; $body = $message; $email_from = "email@example.com"; 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.
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.