PHP provides the mail() function for easy sending of mail from your PHP server. The problem is that sending HTML email (the most popular format for emails) is not easily done using native PHP functions. I’ve provided below a somewhat foolproof function that will allow you to send HTML emails.
Simply pass in a to address, from address, from name (which is used as a nickname in email clients instead of displaying the sender’s email address), subject, and a properly formatted HTML email message.
If you are sending to multiple recipients, you can pass the $to_email parameter in as an array of multiple email addresses.
function send_email ($to_email, $from_email, $from_name, $subject, $msg) {
//split up to email array, if given
if (is_array($to_email)) {
$to_email_string = implode(', ', $to_email);
}
else {
$to_email_string = $to_email;
}
//Assemble headers
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: $from_name <$from_email>" . "\r\n";
//send via PHP's mail() function
mail($to_email_string, $subject, $msg, $headers);
}
You call the function like this:
send_email("me@gmail.com", "roger@att.com", "Roger", "Hello There",
"<html>Hello There <strong>Bob</strong>! How are you doing</html>!");
Or, alternately, you call it like this when sending to multiple email addresses:
send_email(array("me@gmail.com", "sal@gmail.com"), "roger@att.com",
"Roger", "Hello There",
"<html>Hello There <strong>Bob</strong>! How are you doing</html>!");
Remember that formatting HTML for email is different than for webpages. Do not use a CSS file and do not declare CSS in the head of your document. Instead, use either inline CSS or “Old School” HTML like font tags for formatting. Also, don’t use JavaScript, as major email clients don’t support it.
Though it may seem obvious, remember that images and links within your HTML email need to be full, absolute paths to their world wide web accessible location. No relative links!