【问题标题】:Sending an email with php plain text and html使用 php 纯文本和 html 发送电子邮件
【发布时间】:2012-04-22 12:14:34
【问题描述】:

我有以下电子邮件标题:

$random_hash = md5(date('r', time()));
    $headers = array ('From' => $from,
   'To' => $to,
    'Return-Path' => 'info@example.com',
   'Subject' => $subject,
     'Content-Type'=>'multipart/alternative');

我想在一封电子邮件中发送两个版本的电子邮件。一个文本和一个 html。

所以我这样做了:

ob_start(); ?>
 --PHP-alt-<?php echo $random_hash; ?>
    Content-Type: text/plain; charset="iso-8859-1" 
    Content-Transfer-Encoding: 7bit
    Copy and paste: http://example.com/app_dl.php?app_id=<?php echo $_GET[app_id]; ?> to download your $app_name app \r\n
     Want to get tons more hot apps for free! anywhere anytime? Download our app on http://example.com  \r\n
     example.com team;

--PHP-alt-<?php echo $random_hash; ?>  
    Content-Type: text/html; charset="iso-8859-1" 
    Content-Transfer-Encoding: 7bit
     <p><a href='http://example.com/app_dl.php?app_id=<?php echo $_GET[app_id]; ?>'>Click Here</a> to download your <?php echo $app_name_app; ?></p>
     <p>Want to get tons more hot apps for free! anywhere anytime? Download our app on <a href='http://example.com'>example.com</a></p>
     <br/>
     <p>example.com team</p>";


     <?php 
      $bodyHTML =ob_get_clean();

但它似乎效果不佳..我想知道为什么!?!?

【问题讨论】:

  • 嗯,你为什么要手动创建所有的 MIME,而不是为它使用一个只指定 HTML 和文本内容的类?
  • 1.定义“效果不佳”。 2.“Content-Type”和“Content-Transfer-Encoding”应该是headers的一部分。
  • @TheSimon,它们是报头的一部分,问题是多部分消息中的部分没有分开......
  • @mario,重复吗? PHPMailer 和 Swiftmailer 与此有​​什么关系?
  • @DmitryMakovetskiyd:你错了。 Stackoverflow 不是个人代码修复服务。只是从第一个谷歌结果中复制和粘贴并不是什么研究。你仍然没有费心去进一步搜索,也没有真正尝试理解你得到的答案。

标签: php email


【解决方案1】:

为了创建multipart/alternative 消息,您需要指定boundary 并用该边界分隔每个部分。一个好的边界字符串是消息部分本身极不可能出现的东西,例如由sha1(uniqid()) 生成的随机字符串。例如:

MIME-Version: 1.0
Content-Type: multipart/alternative; boundary=c4d5d00c4725d9ed0b3c8b

--c4d5d00c4725d9ed0b3c8b
Content-Type: text/plain; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

part1

--c4d5d00c4725d9ed0b3c8b
Content-Type: text/html; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

<b>part2</b>

--c4d5d00c4725d9ed0b3c8b--

这是在RFC 2046, section 5.1.4 中指定的。

【讨论】:

  • 有关这方面的工作示例,请参阅文章“PHP: Sending Email (Text/HTML/Attachments)”中的“发送带有附件的电子邮件”部分。
  • 这就是我现在正在阅读的文章..查看更新
  • @DmitryMakovetskiyd,阅读 RFC 或我的回答,您会发现需要在内容类型标头中指定边界,并且还需要关闭边界。
  • 好吧,我错了,是我没有关闭边界
  • @DmitryMakovetskiyd,以及您没有在内容类型标题中指定边界的事实。
【解决方案2】:

我发现使用 PHP_EOL 而不是 \r\n 似乎也可以。例如:

$headers = "Content-type: text/html; charset=UTF8" . PHP_EOL;

【讨论】:

  • PHP_EOL 基于您使用的平台。因此,如果您使用在 Linux 上运行的相同脚本并将其移动到 Windows 机器上,它将开始发送“\n”而不是“\r\n”,这可能不是您想要的。
猜你喜欢
  • 1970-01-01
  • 2017-06-28
  • 1970-01-01
  • 2012-04-29
  • 1970-01-01
  • 1970-01-01
  • 2013-03-25
  • 2021-07-06
  • 1970-01-01
相关资源
最近更新 更多