Send PHP HTML mail with attachments

前端 未结 4 2058
清歌不尽
清歌不尽 2020-11-30 02:41

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

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 03:13

    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);
    }
    

提交回复
热议问题