简体   繁体   English

电子邮件正文为空,MIME为多部分(文本和HTML)

[英]Email body is empty, MIME multipart (text & html)

I can send just text fine, just html fine, but when I combine the two as follows the email sends but the body is empty. 我可以只发送文本,也可以只发送html,但是当我将以下两者结合时,电子邮件将发送,但正文为空。

$to = "some@email.com";
$subject = "Welcome";
$boundary = md5(date('U'));

$headers = "From: Company <noreply@email.com>" . "\n".
                   "X-Mailer: PHP/".phpversion() ."\n".
                   "MIME-Version: 1.0" . "\n".
                   "Content-Type: multipart/alternative; boundary=".$boundary. "\n";
                   "Content-Transfer-Encoding: 7bit". "\n";

// TEXT EMAIL PART
$text = "Congratulations";

// HTML EMAIL PART
$html = "<html><body>\n";
$html .= "<div>Congratulations</div>";
$html .= "</body></html>\n";

$message = "Multipart Message coming up" . "\n\n".
           "--".$boundary.
           "Content-Type: text/plain; charset=\"iso-8859-1\"" .
           "Content-Transfer-Encoding: 7bit".
           $text. 
           "--".$boundary. 
           "Content-Type: text/html; charset=\"iso-8859-1\"". 
           "Content-Transfer-Encoding: 7bit". 
           $html.
           "--".$boundary."--";

mail($to, $subject, $message, $headers);    

You've forgotten line breaks after your Content-Type and Content-Transfer-Encoding lines, so the beginnings of your body content are co-mingled with the headers: 您忘记了Content-Type和Content-Transfer-Encoding行之后的换行符,因此正文内容的开头与标头混合在一起:

       "--".$boundary.
                    ^^^--- missing \n
       "Content-Transfer-Encoding: 7bit".
                                        ^^^--- missing \n\n
       $text. 

As stated in the comments above, use Swiftmailer or PHPMailer to do this. 如上面的评论所述,使用SwiftmailerPHPMailer可以做到这一点。 They'll take care of all the piddle little details, and let you send the entire mail in far fewer lines of code. 他们将处理所有棘手的小细节,并让您以更少的代码行发送整个邮件。

$boundary is was undefined, you don't have a line break before or after any of the boundaries, and you don't have a blank line between the headers and body of each part (or a line break after any of those headers). 是未定义的,您在任何边界之前或之后都没有换行符,并且在各部分的标题和主体之间没有空白行(或在任何这些标题之后都有换行符)。

Don't handroll MIME. 不要传递MIME。 I'm sure there is a decent library for PHP that will do it for you. 我确定有一个不错的PHP库可以为您完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM