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 = ''
$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:\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('')));

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

This is a test email message sent with PHP.

Content-Type: application/zip;
Content-Transfer-Encoding: base64
Content-Disposition: attachment


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

, ,