Skip to content

Instantly share code, notes, and snippets.

@davidnknight
Created July 20, 2012 12:01
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save davidnknight/3150361 to your computer and use it in GitHub Desktop.
Save davidnknight/3150361 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link

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

@GrimalDev
Copy link

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