php - 使用 PHP mail() 发送多部分/替代

标签 php html-email multipart-alternative

所以我尝试使用 PHP 发送一个相当简单的 HTML 电子邮件。在过去的三天里,我一直在寻找一个好的解决方案,并认为我找到了一个,但是当我测试它时,它没有正确发送。我从我引用的其中一个教程中借用了这段代码。测试代码如下:

<?php
//define the receiver of the email
$to = 'myemail@gmail.com';
//define the subject of the email
$subject = 'Test HTML email'; 
//create a boundary string. It must be unique 
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time())); 
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"".$random_hash."\""; 
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--<?php echo $random_hash; ?>  
Content-Type: text/plain; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

Hello World!!! 
This is simple text email message. 

--<?php echo $random_hash; ?>  
Content-Type: text/html; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p> 

--<?php echo $random_hash; ?>--
<?
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed";
?>

问题是,虽然它可以很好地发送电子邮件,但它要么以纯文本形式发送,要么在 Gmail 中发送空白邮件。任何想法为什么?

最佳答案

我当然应该告诉你为此使用一个库,比如 swift,但我认为这是一个很好的练习,所以我会告诉你它有什么问题:)

这是因为你的行尾错误。除非另有说明,否则电子邮件中的行结尾是 CRLF (\r\n),而您的 ob_start() block 可能只有 LF (\n ) 作为行分隔符。

这会导致 GMail 错误解释电子邮件信息,而不是显示任何内容。在我的例子中,它显示了一个空的下载文件;)

关于php - 使用 PHP mail() 发送多部分/替代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12117324/

相关文章:

iphone - 带有内联图像的 html 电子邮件在 iphone 中无法正确呈现

HTML 电子邮件 - Outlook 2013 中图像之间的间隙

php - 使用 Swift Mailer 发送多部分/替代邮件

wordpress - 内容类型:带有 wp_mail() 的 Wordpress 中的 multipart/alternative

javascript - jQuery 延迟加载图像和视频不起作用

php - 如何获取 Apache 版本

php - 第一次数据支付网关集成soap故障报错

PHP:cURL 会在后台完成,还是会阻止所有进一步的脚本执行?

email - 控制 HTML 电子邮件通讯的自动预览文本的最佳方法是什么?