Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

Send PHP HTML mail with attachments

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.">
";
$header .= "Reply-To: ".$replyto."
";
$header .= "MIME-Version: 1.0
";
$header .= "Content-Type: multipart/mixed; boundary="".$uid.""

";
$header .= "This is a multi-part message in MIME format.
";
$header .= "--".$uid."
";
$header .= "Content-type:text/html; charset=iso-8859-1
";
$header .= "Content-Transfer-Encoding: 7bit

";
$header .= $message."

";

    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."
";
        $header .= "Content-Type: application/octet-stream; name="".$filename.""
"; // use different content types here
        $header .= "Content-Transfer-Encoding: base64
";
        $header .= "Content-Disposition: attachment; filename="".$filename.""

";
        $header .= $content."

";
    }

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...