使用Content-Type发送PHP邮件:multipart / alternative

问题描述 投票:5回答:3

我正在尝试发送包含html和纯文本的多部分邮件。这也是通过垃圾邮件过滤器以及允许更多人在不支持HTML的情况下阅读邮件的方法之一。在花了很长时间谷歌搜索后,我找到了一些例子。我制作了我的代码,它发送邮件,但它显示带有html标签,代码,字符串等的文本。

<?php
$boundary=md5(uniqid(rand()));
$header .= "From:My Name<[email protected]>\n";
$header .= "Reply-To: [email protected] \n";
$header .= 'MIME-Version: 1.0'."\r\n";
$header .= 'Content-type: multipart/alternative;boundary=$boundary '."\n";

$adres = "[email protected]";

$subject = "subject";

$message = "This is multipart message using MIME\n";
$message .= "--" . $boundary . "\n";
$message .= "Content-type: text/plain;charset=iso-8859-1\n";
$message .= "Content-Transfer-Encoding: 7bit". "\n\n";
$message .= "Plain text version\n\n";
$message .="--" . $boundary . "\n";
$message .="Content-type: text/html;charset=iso-8859-1\n";
$message .= "Content-Transfer-Encoding: 7bit". "\n\n";
$message .="<html>
<body>
<center>
<b>HTML text version</b>
</center>
</body>
</html>\n\n";
$message .= "--" . $boundary . "--";

if(mail($adres, $subject, $message, $header))
{
print'message sent';
}
else
{
print'message was not sent';
}
?>

这是结果:

    This is multipart message using MIME
    --c071adfa945491cac7759a760ff8baeb
    Content-type: text/plain;charset=iso-8859-1
    Content-Transfer-Encoding: 7bit

    Plain text version

    --c071adfa945491cac7759a760ff8baeb
    Content-type: text/html;charset=iso-8859-1
    Content-Transfer-Encoding: 7bit

    <html>
    <body>
    <center>
    <b>HTML text version</b>
    </center>
    </body>
    </html>

    --c071adfa945491cac7759a760ff8baeb--

正如您所看到的,它只显示编码而不是消息。我尝试了许多解决方案,如:

  • 添加/删除\ r \ n;
  • 将\ r \ n更改为\ n;
  • 将内容类型从替代变为混合;

我正在学习PHP,我所知道的就是我到目前为止所阅读和完成的所有知识。如果你能告诉我问题在哪里,我还有很多东西要学习。我会非常感激。最诚挚的问候。

php html email mime multipart
3个回答
3
投票

这条线:

$header .= 'Content-type: multipart/alternative;boundary=$boundary '."\n";

有错误的报价,所以$boundary将不会扩大。改成:

$header .= "Content-type: multipart/alternative;boundary=$boundary\n";

就像我在评论中所说的那样,在消息头和内容部分标题中,您应该使用\r\n作为换行符,因为这是RFC中定义的内容。大多数MTA只允许使用\n,但有些会阻塞消息,而一些垃圾邮件过滤器会将每次RFC违规都计入垃圾邮件分数。

使用像PHPMailer这样的东西是一个更好的选择,因为它默认情况下完美地格式化了所有内容,并且遵守几乎每一个模糊,无聊的RFC。


0
投票

我认为你需要围绕边界字符串的引号。

试试这个:

$header    .= 'Content-type: multipart/alternative; boundary="' . $boundary . '"\r\n';

0
投票

试试这个例子https://github.com/breakermind/PhpMimeParser/blob/master/PhpMimeClient_class.php

$m = new PhpMimeClient();
// Add to
$m->addTo("[email protected]", "Albercik");
$m->addTo("[email protected]", "Adela");
// Add Cc
$m->addCc("[email protected]");
// Add Bcc
$m->addBcc("[email protected]", "BOSS");    
// Add files inline
$m->addFile('photo.jpg',"zenek123");
// Add file
$m->addFile('sun.png');
// create mime
$m->createMime("Witaj!",'<h1>Witaj jak się masz? <img src="cid:zenek123"> </h1>',"Wesołych świąt życzę!","Heniek Wielki", "[email protected]");
// get mime
// $m->getMime();
// Show mime
echo nl2br(htmlentities($m->getMime()));
© www.soinside.com 2019 - 2024. All rights reserved.