SendGrid会自动将HTML邮件转换为纯文本吗?

时间:2016-06-30 18:01:45

标签: c# asp.net-mvc sendgrid

我向注册的用户发送确认电子邮件,并希望确保在用户的电子邮件客户端不显示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>

2 个答案:

答案 0 :(得分:1)

您可以使用HtmlAgilityPack(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视图并将plainText作为电子邮件主题发送。      ContentType mimeType = new ContentType(“text / html”);      AlternateView alternate = AlternateView.CreateAlternateViewFromString(htmlString,mimeType);

答案 1 :(得分:0)

您必须自己提供文字替代方案。您可以通过将 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);