Posts Tagged boundary

Send email attachment with PHP

Everybody probably knows how to send an email using PHP, but do you know how to send an email with an attachment?

This is actually not very difficult and you can find examples all over the web. However, it seems that all the examples I found didn’t work! 🙁
But after some debugging and testing, I finally got a working solution. 😀

Please see below the code with comments:

// Define some variables
$to = 'test@logikdev.com'
$subject = 'Test email';
// Create a boundary string. It must be unique so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));

// Define the headers
$headers = "From: noreply@logikdev.com\r\n";
// Add boundary string and mime type specification
$headers .= "Content-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";

// Read the attachment file contents into a string, encode it with MIME base64, and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));

// Define the body of the message
$message = "
--PHP-mixed-$random_hash
Content-Type: text/plain; charset='iso-8859-1'

This is a test email message sent with PHP.

--PHP-mixed-$random_hash
Content-Type: application/zip; name=attachment.zip
Content-Transfer-Encoding: base64
Content-Disposition: attachment

$attachment
--PHP-mixed-$random_hash--";

// Send the email
if (@mail($to, $subject, $message, $headers)) {
	echo "The mail has been sent.";
} else {
	echo "The mail has NOT been sent!";
}

, ,

3 Comments