Created
July 20, 2012 12:01
-
-
Save davidnknight/3150361 to your computer and use it in GitHub Desktop.
PHP Send Mail (Plaintext and HTML)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Send email | |
* @param string|array $email | |
* @param object $from | |
* @param string $subject | |
* @param string $message | |
* @param string $headers optional | |
*/ | |
function send_email($email, $from, $subject, $message, $headers = null) | |
{ | |
// Unique boundary | |
$boundary = md5( uniqid() . microtime() ); | |
// If no $headers sent | |
if (empty($headers)) | |
{ | |
// Add From: header | |
$headers = "From: " . $from->name . " <" . $from->email . ">\r\n"; | |
// Specify MIME version 1.0 | |
$headers .= "MIME-Version: 1.0\r\n"; | |
// Tell e-mail client this e-mail contains alternate versions | |
$headers .= "Content-Type: multipart/alternative; boundary=\"$boundary\"\r\n\r\n"; | |
} | |
// Plain text version of message | |
$body = "--$boundary\r\n" . | |
"Content-Type: text/plain; charset=ISO-8859-1\r\n" . | |
"Content-Transfer-Encoding: base64\r\n\r\n"; | |
$body .= chunk_split( base64_encode( strip_tags($message) ) ); | |
// HTML version of message | |
$body .= "--$boundary\r\n" . | |
"Content-Type: text/html; charset=ISO-8859-1\r\n" . | |
"Content-Transfer-Encoding: base64\r\n\r\n"; | |
$body .= chunk_split( base64_encode( $message ) ); | |
$body .= "--$boundary--"; | |
// Send Email | |
if (is_array($email)) | |
{ | |
foreach ($email as $e) | |
{ | |
mail($e, $subject, $body, $headers); | |
} | |
} | |
else | |
{ | |
mail($email, $subject, $body, $headers); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
A simple function for sending email(s) using PHP's built in mail function. This function will send both html and plain text versions in the email. | |
Notes: | |
This first parameter ($email) of this function will accept one email as a string or an array of emails. | |
The second parameter ($from) is an object with two properties; $from->name and $from->email. |
Today you can use charset=UTF-8
instead of charset=ISO-8859-1
.
PHP 8.2 good practices would be to add types for the parameters and a return type. Thanks for the function !
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
uniqid()
is alreadymicrotime()
based. REF: https://www.php.net/manual/en/function.uniqid.phpIt is recommended that you use
uniqid('',TRUE)
if you want more guarantee of uniqueness.