Send PHP HTML mail with attachments

Florian Müller picture Florian Müller · Mar 1, 2012 · Viewed 67.5k times · Source

I got a problem: Until today, I sent HTML mails with PHP using a header which contains

Content-type: text/html;

Now, I added functionality to add attachments. For this, I had to change this line to

Content-Type: multipart/mixed;

Now, with multipart/mixed, the rest of the mail, so the normal text, gets shown just as text/plain. How can I realize that attachments work and the mailtext is still HTML?

Answer

Brian picture Brian · Nov 19, 2012

I tried Answer 1 for a couple of hours with no luck. I found a solution here: http://www.finalwebsites.com/forums/topic/php-e-mail-attachment-script

Works like a charm- less than 5 min! You might want to change (like I did), the first content type from text/plain to text/html.

Here is my slightly modified version to handle multiple attachments:

function mail_attachment($files, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
$uid = md5(uniqid(time()));

$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/html; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";

    foreach ($files as $filename) { 

        $file = $path.$filename;

        $file_size = filesize($file);
        $handle = fopen($file, "r");
        $content = fread($handle, $file_size);
        fclose($handle);
        $content = chunk_split(base64_encode($content));

        $header .= "--".$uid."\r\n";
        $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
        $header .= "Content-Transfer-Encoding: base64\r\n";
        $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
        $header .= $content."\r\n\r\n";
    }

$header .= "--".$uid."--";
return mail($mailto, $subject, "", $header);
}