Tuesday, July 23, 2013

Email with File Attachment in PHP

While working in a project i was stuck with this File Attachment problem. The requirement was to generate an Invoice(PDF) at run-time and email it to user. After hours of searching and testing finally i found the solution. Following is the code :

// array with file names to be sent as attachment
$files = array("abcd.pdf","efgh.pdf");
// email fields: to, from, subject, and so on
$to = "receiver@gmail.com";
$from = "Sender Name "."";
$subject ="Your attached file";
$message = "My message";
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
for($x=0;$x{
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
$ok = @mail($to, $subject, $message, $headers);
if ($ok) {
echo "mail sent to $to!
";
} else {
echo "mail could not be sent!
";
}
The above code is tested and working fine. The only changes required are :

1) Add file name to array. With this code you can attach multiple files in mail. Just add file name to array.
$files = array("abcd.pdf","efgh.pdf");

2) Change sender email
$from = "Sender Name "."";

3) Change receiver email
$to = "receiver@gmail.com";

4) Change your message
$message = "My message";

Make sure in your message part you put only text and not html because html tags don't work here as Content-Type is set to  text/plain.

So, this was all about attaching file with email. Feel free to comment or ask using contact form. Stay tuned form more updates.

No comments :

Post a Comment