dongyoucha0645 2014-09-16 15:42
浏览 15
已采纳

将PHPMailer HTML消息转换为文本消息

I wish to send an email using HTML if allowed by the client, else text. Something like the following:

$mail = new PHPMailer();
$htmlMessage="Hello John,<br /><br />How are you?";
$textMessage="Hello John,

How are you?";
$mail->Body =  $htmlMessage; 
$mail->AltBody  =  $textMessage;

I don't wish to write out the whole message for both, however, but create one version, and automatically convert it to the second.

Given this exact message, should I just create $textMessage, and then use nl2br() to add the HTML line breaks?

What if my HTML message was a bit more complicated and included bold text, a list, etc? I am okay with the Text message being somewhat ugly, but don't want a bunch of HTML tags in the message. What are my options for this scenario?

  • 写回答

2条回答 默认 最新

  • duanjiaopi8218 2014-09-16 16:52
    关注

    Er, you do know that PHPMailer has two built-in HTML to plain text converters? Strip_tags is a pretty poor solution - it often results in an unreadable mess. The best results I've got come from using a real text-based browser (specifically elinks) which can make a great job of rendering HTML as text, able to do things like preserve multi-column layouts, underlining, link references and some CSS. However, shelling out isn't always an option, so PHP solutions exist.

    PHPMailer does an automatic conversion for the plain text version in msgHTML(), so your code would simply be this:

    $mail = new PHPMailer();
    $htmlMessage="Hello John,<br /><br />How are you?";
    $mail->msgHTML($htmlMessage);
    

    There is an option for a slightly more advanced converter (bundled in the extras folder) which you can trigger by setting the 'advanced' param in msgHTML:

    $mail->msgHTML($htmlMessage, '', true);
    

    Try them both, see what works best for you - but it's always worth reading the docs and source code!

    Update Since I posted this answer, PHPMailer has had to remove the bundled html2text class for license reasons, but the mechanism for plugging in your own converter has been improved - the advanced parameter can now be a closure through which you can implement your own converter, such as any of those you might find on packagist.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!