使用php纯文本和html发送电子邮件

时间:2012-04-22 12:14:34

标签: php email

我有以下电子邮件标题:

$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();

但它看起来效果不好......我想知道为什么!?!?

2 个答案:

答案 0 :(得分:16)

要创建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中指定。

答案 1 :(得分:-1)

我发现使用PHP_EOL代替\ r \ n似乎也能正常工作。例如:

HTTP/1.1 200 OK
Server: GlassFish Server Open Source Edition  4.1
x-powered-by: Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition  4.1  Java/Oracle Corporation/1.7)
Content-Type: application/json; charset=utf-8
Date: Tue, 13 Oct 2015 11:33:57 GMT
Content-Length: 103