Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP Send Mail (Plaintext and HTML)
<?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);
}
}
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.
@volomike

This comment has been minimized.

Copy link

volomike commented May 29, 2019

uniqid() is already microtime() based. REF: https://www.php.net/manual/en/function.uniqid.php

It is recommended that you use uniqid('',TRUE) if you want more guarantee of uniqueness.

@volomike

This comment has been minimized.

Copy link

volomike commented May 29, 2019

Today you can use charset=UTF-8 instead of charset=ISO-8859-1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.