Skip to content

Instantly share code, notes, and snippets.

@serialc
Created September 9, 2021 14:36
Show Gist options
  • Save serialc/985028007a326a879ef31e841abb2a56 to your computer and use it in GitHub Desktop.
Save serialc/985028007a326a879ef31e841abb2a56 to your computer and use it in GitHub Desktop.
How to send an email from PHP that is well formed. Failure to provide all the necessary and well structured information can result in email contents being placed in attachments rather than in email content.
<?php
# This is a fragment, needs to be integrated
# This doesn't send the sender's information - uses the system's email
# parameters to customize, perhaps in a function
$to_name = "MJ Watson";
$to_email = "mjwatson@marvel.com";
#$from_name = "P Parker";
#$from_email = "pparker@marvel.com;
$subject = "test email";
$msg = "message contents";
# constants
$eol = "\r\n";
# headers so that they are received nicely
$headers = array();
# main header (multipart mandatory)
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-Type: text/html; charset=iso-8859-1';
$headers[] = "To: $to_name <$to_email>";
# prep message
$message = "<html>";
$message .= "<head><title>$subject</title><meta http-equiv='content-type' content='text/html; charset=utf-8' /></head>";
$message .= "<body>$msg</body>"
$message .= "</html>";
# warning, trying to send as an array causes php to insert bad line carriage returns
# this causes the email to be treated as text rather than html - hence the implode below
if( mail($to_name, $subject, $message, implode($eol, $headers)) ) {
# Email sent succesfully
# Perhaps you wish to cut this out and replace with some internal error logging
print("<html><head><meta http-equiv='refresh' content='5; URL=http://my.website.com' /><title>email sent</title></head>");
print("<body><h1>Email sent!</h1><p>Thank you! We will try to respond as soon as possible.</p>");
print("<p>You will be redirected to the main page shortly</p>");
print("</body></html>");
} else {
# Failed to send the email - return a message to the user
# Perhaps you wish to cut this out and replace with some internal error logging
header("HTTP/1.1 500 OK");
print('<html><head><title>email not sent</title></head>');
print('<body><h1>Email not sent!</h1><p>Sorry about that!</p>');
print('<p>Could you please send an email to spider@support.com letting us know why you were reaching out?</p>');
print('<p>Sorry for the inconvenience.</p>');
print('<p>If you\'re willing, could you please also send the following message:</p>');
nl2br(print_r(error_get_last(), true));
print('</body></html>');
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment