所以我尝试使用 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/