Skip to content
Web designer & photographer

php mail() multiple attachments solution

by Lukas on March 18th, 2010

If you need a solution for multiple attachments in PHP using mail() function take a look below. Code below allows to attach and send 2 files. If you still having problems just take a look at raw email file. Each attachment needs to be divided by mime boundary (same boundary for each file) and this boundary needs to be added at the end of our message.


$logo = $_FILES['logo']['tmp_name'];
$logo_type = $_FILES['logo']['type'];
$logo_name = $_FILES['logo']['name'];
$image      = $_FILES['image']['tmp_name'];
$image_type = $_FILES['image']['type'];
$image_name = $_FILES['image']['name'];

headers = "From: no-reply@mydomainhere.co.uk";
if (is_uploaded_file($logo)) {
$file = fopen($logo,'rb');
$data = fread($file,filesize($logo));
fclose($file);

 Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "{$semi_rand}";
$rand_id = md5($semi_rand);

Add the headers for a file attachment
$headers .= "nMIME-Version: 1.0n" .
"Content-Type: multipart/mixed;n" .
" boundary="{$mime_boundary}"";

Add a multipart boundary above the plain message
$message = "--{$mime_boundary}n" .
"Content-Type: text/plain; charset="iso-8859-1"n" .
"Content-Transfer-Encoding: 7bitnn" .
"Name : $_POST[name] nn" .
"Address : $_POST[address] nn" .
"Description: $_POST[description] nn";

Base64 encode the file data
$data = chunk_split(base64_encode($data));

Add file attachment to the message
$message .= "--{$mime_boundary}n" .
"Content-Type: {$logo_type}; name="{$logo_name}"n" .
"Content-Disposition: attachment; filename="{$logo_name}"n" .
"Content-Transfer-Encoding: base64n" .
"X-Attachment-Id: file_{$rand_id}nn" .
$data . "nn";
}

 Second attachment
if (is_uploaded_file($image)) {
 Read the file to be attached ('rb' = read binary)
$file = fopen($image,'rb');
$data = fread($file,filesize($image));
fclose($file);

 Base64 encode the file data
$data = chunk_split(base64_encode($data));

 Add file attachment to the message
$message .= "--{$mime_boundary}n" .
"Content-Type: {$image_type}; name="{$image_name}"n" .
"Content-Disposition: attachment; filename="{$image_name}"n" .
"Content-Transfer-Encoding: base64n" .
"X-Attachment-Id: file_{$rand_id}nn" .
$data . "nn" .
"--{$mime_boundary}--n";
}

Send the message
$ok = @mail("confirmations@mydomainhere.co.uk", $subject, $message, $headers);
if ($ok) {
echo "OK!";
} else {
echo "Error!!";
}
}

 

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

From → Web Development

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS