所以我试图用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中发送空白邮件。有什么想法吗?
答案 0 :(得分:7)
我当然应该告诉你使用一个库,比如swift,但我认为这是一个很好的练习,所以我会告诉你它有什么问题:)
这是因为你的行结尾是错误的。除非另有说明,否则电子邮件中的行结尾为CRLF(\r\n
),而您的ob_start()
块可能只有LF(\n
)作为行分隔符。
这会导致GMail误解电子邮件,而不会显示任何内容。在我的情况下,它显示一个空的下载文件;)