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条)

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端