小编典典

从PHP发送HTML电子邮件

html

我正在尝试从PHP发送简单的HTML电子邮件。下面的代码仅导致GMail中的空白电子邮件。它还有一个名为“
noname”的空附件,这根本不是我想要的;尽管那可能只是它无法正常工作的症状。

我使用的代码是:

<?php
//define the receiver of the email
$to = 'morrillkevin@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=\"PHP-alt-".$random_hash."\"";
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-alt-<?php echo $random_hash; ?> 
MIME-Version: 1.0
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

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

--PHP-alt-<?php echo $random_hash; ?> 
MIME-Version: 1.0
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-alt-<?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";

阅读 306

收藏
2020-05-10

共1个答案

小编典典

原来关键是编码类型。代替:

Content-Type: text/plain; charset="iso-8859-1"

我需要使用:

Content-Type: text/plain; charset=us-ascii

它可能取决于您如何在自己的文本编辑器中保存PHP文件的细节。我没有研究它,但是PHP中的 iconv
函数可能也给我带来了一些乐趣。所以我认为这部分确实很敏感。

这是一个更好的示例代码片段,以端到端的方式展示了整个过程:

$notice_text = "This is a multi-part message in MIME format.";
$plain_text = "This is a plain text email.\r\nIt is very cool.";
$html_text = "<html><body>This is an <b style='color:purple'>HTML</b> text email.\r\nIt is very cool.</body></html>";

$semi_rand = md5(time());
$mime_boundary = "==MULTIPART_BOUNDARY_$semi_rand";
$mime_boundary_header = chr(34) . $mime_boundary . chr(34);

$to = "Me <foo@gmail.com>";
$from = "Me.com <me@me.com>";
$subject = "My Email";

$body = "$notice_text

--$mime_boundary
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

$plain_text

--$mime_boundary
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: 7bit

$html_text

--$mime_boundary--";

if (@mail($to, $subject, $body,
    "From: " . $from . "\n" .
    "MIME-Version: 1.0\n" .
    "Content-Type: multipart/alternative;\n" .
    "     boundary=" . $mime_boundary_header))
    echo "Email sent successfully.";
else
    echo "Email NOT sent successfully!";

exit;
2020-05-10