2016-06-30 3 views
0

등록한 사용자에게 확인 이메일을 보내고 있으며 사용자의 이메일 클라이언트에 HTML이 표시되지 않는 경우를 대비하여 HTML과 일반 텍스트 버전이 모두 있는지 확인하고 싶지만 어떻게해야합니까? 이 작업을 수행. 다음은 내 코드 중 일부입니다.SendGrid가 HTML 메시지를 일반 텍스트로 자동 변환합니까?

private async Task configSendGridasync(IdentityMessage message) 
    { 
     var myMessage = new SendGridMessage(); 
     myMessage.AddTo(message.Destination); 
     myMessage.From = new System.Net.Mail.MailAddress(
          "[email protected]", "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> 
+0

아니요 자동으로 변환하지 않습니다. 일반 텍스트를 제공해야합니다. – Stilgar

답변

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); 
+0

이것은 좋은 길로 보입니다. 그러나 유일한 문제는 내 HTML이 이제 한 줄에 완전히 있고 내가 사용하고 있던 링크가 없어 졌기 때문입니다. 링크가 : click here ~ : www.examplelink.com – Brett

+0

원래 게시물을 편집하고 내가 사용하는 HTML 유형에 대한 더 나은 예제를 추가했습니다. – Brett

+0

다른 정규 표현식을 사용하여 링크에서 href 속성을 추출 할 수 있습니다 :' longchiwen

1

당신은 HTML에서 일반 텍스트로 변환 수행 할 HtmlAgilityPack (NuGet)를 사용할 수 있습니다

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 = plain 본문;

이벤트 나는 대체 HTML보기를 작성하고 plainText를 전자 메일 제목으로 보냅니다. ContentType mimeType = 새 ContentType ("text/html"); 대체보기 대체 = AlternateView.CreateAlternateViewFromString (htmlString, mimeType);

관련 문제