电子邮件正文为空,MIME 多部分(文本和 html)
我可以只发送文本,也可以发送 html,但是当我将两者结合起来时,电子邮件会发送,但正文是空的。
$to = "[email protected]";
$subject = "Welcome";
$boundary = md5(date('U'));
$headers = "From: Company <[email protected]>" . "\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);
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.
$to = "[email protected]";
$subject = "Welcome";
$boundary = md5(date('U'));
$headers = "From: Company <[email protected]>" . "\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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您忘记了 Content-Type 和 Content-Transfer-Encoding 行之后的换行符,因此正文内容的开头与标题混合在一起:
如上面的评论所述,请使用 Swiftmailer 或 PHPMailer 来执行此操作。他们会处理所有琐碎的小细节,并让您用更少的代码行发送整个邮件。
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:
As stated in the comments above, use Swiftmailer or PHPMailer to do this. 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未定义,任何边界之前或之后都没有换行符,并且标题和正文之间没有空行每个部分(或任何这些标题后的换行符)。不要手动处理 MIME。我确信有一个不错的 PHP 库可以为您做到这一点。
$boundary
iswas 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. I'm sure there is a decent library for PHP that will do it for you.