无法发送带附件的html邮件

时间:2014-05-13 10:54:17

标签: php email

使用的Php代码:

    $boundary = uniqid("np");

    $header = "MIME-Version: 1.0\r\n" ;
    $header .= "From: $from\r\n";
    $header .= "To: $to\r\n";
    if (!is_null($reply_to)) $header .= "Reply-To: $reply_to \r\n";
    $header .= "Content-Type: multipart/mixed;boundary=" . $boundary . "\r\n";

    //here is the content body
    $message = "This is a multi part message in MIME format.\n\n";

    $message .= "--" . $boundary . "\n";
    $message .= "Content-type: text/html;charset=utf-8\n\n";

    $message .= "Hello, <BR> This is a text email, the <bold>html version</bold>.";
    $message .= "<BR>Regards";
    $message .= "<BR>Your Name";
    $message .= "\n\n--" . $boundary . "\n";

    $file_name = "file_01.txt";
    $file_content = "Ciao - file 1";
    $chunked_content = chunk_split(base64_encode($file_content));  

    $message .= "Content-Type: application/octet-stream; name=\"$file_name\"\n";
    $message .= "Content-Disposition: attachment; filename=\"$file_name\"\n"; 
    $message .= "Content-Transfer-Encoding: base64\n\\n" . $chunked_content . "\n\n";  
    $message .= "--{$boundary}--";  

结果: HTML邮件没问题,附件中有正确的文件名,但它是空的

出了什么问题?

编辑:!试图用\ r \ n替换每个\ n但是结果是空邮件。

1 个答案:

答案 0 :(得分:1)

我将以下代码用于电子邮件附件。试试这个

function mailWithAttachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message)
{
    $file = $path.$filename;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));
    $name = basename($file);
    $header = "From: ".$from_name." <".$from_mail.">\n";
    $header .= "Reply-To: ".$replyto."\n";
    $header .= "MIME-Version: 1.0\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\n\n";
    $header .= "This is a multi-part message in MIME format.\n";
    $header .= "--".$uid."\n";
    $header .= "Content-type:text/html; charset=iso-8859-1\n";
    $header .= $message."\n\n";
    $header .= "--".$uid."\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\n";
    $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\n\n";
    $header .= $content."\n\n";
    $header .= "--".$uid."--";
    if(mail($mailto, $subject, "", $header))
    {
        return 1;
    }
    else
    {
        return 0;
    }
}