【问题标题】:Sending multipart/alternative with PHP mail()使用 PHP mail() 发送 multipart/alternative
【发布时间】:2012-08-20 11:39:20
【问题描述】:

所以我正在尝试使用 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 中发送空白邮件。任何想法为什么?

【问题讨论】:

    标签: php html-email multipart-alternative


    【解决方案1】:

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

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

    这会导致 GMail 误解电子邮件消息,而不会显示任何内容。在我的情况下,它显示一个空的下载文件;)

    【讨论】:

    • 一个空的下载文件正是我得到的!我最终寻找另一个教程并从头开始。不过感谢您的快速回复!
    • 当然。图书馆是必不可少的。在 PHP 中将您自己的符合 RFC 的电子邮件粘合在一起并不是我最大的敌人所希望的。如果您的电子邮件不完全合规,它们通常更有可能被标记为垃圾邮件。做错的风险太高了。
    • 我在使用 \r\n 时遇到了一个问题,Outlook 不会显示我的消息,但 Gmail 会显示。我在这里做了相反的事情,只使用\n 来修复它。太奇怪了,因为我到处都说要使用 CRLF。
    猜你喜欢
    • 2013-09-02
    • 2017-08-08
    • 2013-04-13
    相关资源
    最近更新 更多