SendGrid是否自动将HTML消息转换为纯文本?

本文关键字:转换 文本 消息 HTML 是否 SendGrid | 更新日期: 2023-09-27 17:54:00

我正在向注册的用户发送确认电子邮件,并希望确保有HTML和纯文本版本,以防用户的电子邮件客户端不显示HTML,但我对如何做到这一点有点困惑。下面是我的一些代码:

private async Task configSendGridasync(IdentityMessage message)
    {
        var myMessage = new SendGridMessage();
        myMessage.AddTo(message.Destination);
        myMessage.From = new System.Net.Mail.MailAddress(
                            "hello@example.com", "Example");
        myMessage.Subject = message.Subject;
        myMessage.Text = message.Body;
        myMessage.Html = message.Body;
        var credentials = new NetworkCredential(
                   ConfigurationManager.AppSettings["MailAccount"],
                   ConfigurationManager.AppSettings["MailPassword"]
                   );
        // Create a Web transport for sending email.
        var transportWeb = new Web(credentials);
        // Send the email.
        if (transportWeb != null)
        {
            await transportWeb.DeliverAsync(myMessage);
        }
        else
        {
            Trace.TraceError("Failed to create Web transport.");
            await Task.FromResult(0);
        }
    }

private async Task<string> SendEmailConfirmationTokenAsync(string userID, string subject)
    {
        string code = await UserManager.GenerateEmailConfirmationTokenAsync(userID);
        var callbackUrl = Url.Action("ConfirmEmail", "Account",
           new { userId = userID, code = code }, protocol: Request.Url.Scheme);
        await UserManager.SendEmailAsync(userID, subject, "<p>Example confirmation message</p>");

        return callbackUrl;
    }

我的代码工作并发送HTML电子邮件,但是对于那些拥有不显示HTML的电子邮件客户端的用户会发生什么?myMessage.Text = message.Body;是否自动将"<p>Example confirmation message</p>"转换为纯文本?如果没有,我如何添加一个消息,得到用于文本版本?

编辑:我将使用的HTML格式通常类似于:
<p style="color:#333;">First paragraph</p>
<p style="color:#333;">Second paragraph <a href="https://www.somelink.com">Click here</a></p>
<p style="color:#333;"> Third <br> paragraph</p>

SendGrid是否自动将HTML消息转换为纯文本?

您可以使用htmllagilitypack (NuGet)来完成从html到纯文本的转换:

HtmlToText htt = new HtmlToText();
string plaintText = htt.ConvertHtml(htmlString);

你需要这个htmlcovert。cs:

#region
using System.IO;
#endregion
namespace NameSapceBlah
{
    using HtmlAgilityPack;
    public class HtmlToText
{
    #region Public Methods
    public string Convert(string path)
    {
        HtmlDocument doc = new HtmlDocument();
        doc.Load(path);
        StringWriter sw = new StringWriter();
        this.ConvertTo(doc.DocumentNode, sw);
        sw.Flush();
        return sw.ToString();
    }
    public string ConvertHtml(string html)
    {
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(html);
        StringWriter sw = new StringWriter();
        this.ConvertTo(doc.DocumentNode, sw);
        sw.Flush();
        return sw.ToString();
    }
    public void ConvertTo(HtmlNode node, TextWriter outText)
    {
        string html;
        switch (node.NodeType)
        {
            case HtmlNodeType.Comment:
                // don't output comments
                break;
            case HtmlNodeType.Document:
                this.ConvertContentTo(node, outText);
                break;
            case HtmlNodeType.Text:
                // script and style must not be output
                string parentName = node.ParentNode.Name;
                if ((parentName == "script") || (parentName == "style"))
                    break;
                // get text
                html = ((HtmlTextNode)node).Text;
                // is it in fact a special closing node output as text?
                if (HtmlNode.IsOverlappedClosingElement(html))
                    break;
                // check the text is meaningful and not a bunch of whitespaces
                if (html.Trim().Length > 0)
                {
                    outText.Write(HtmlEntity.DeEntitize(html));
                }
                break;
            case HtmlNodeType.Element:
                switch (node.Name)
                {
                    case "p":
                        // treat paragraphs as crlf
                        outText.Write("'r'n");
                        break;
                }
                if (node.HasChildNodes)
                {
                    this.ConvertContentTo(node, outText);
                }
                break;
        }
    }
    #endregion
    #region Private Methods
    private void ConvertContentTo(HtmlNode node, TextWriter outText)
    {
        foreach (HtmlNode subnode in node.ChildNodes)
        {
            this.ConvertTo(subnode, outText);
        }
    }
    #endregion
}

}

那么你的方法应该工作:myMessage。Text = plainText;

事件,但我会创建一个替代的HTML视图,并发送纯文本作为电子邮件的主题。

 ContentType mimeType = new ContentType("text/html");
 AlternateView alternate =   AlternateView.CreateAlternateViewFromString(htmlString, mimeType);

您必须自己提供文本替代。您可以通过替换br标记为换行符并删除其他html格式来将html转换为文本。例如:

// convert br's to newline
var textString = System.Text.RegularExpressions.Regex.Replace(htmlString, "''s*<''s*[bB][rR]''s*/''s*>''s*", Environment.NewLine);
// remove html tags
textString = System.Text.RegularExpressions.Regex.Replace(textString, "<[^>]*>", string.Empty);