Send HTML email via C# with SmtpClient

后端 未结 6 706
野趣味
野趣味 2020-11-28 08:43

How do I send an HTML email? I use the code in this answer to send emails with SmtpClient, but they\'re always plain text, so the link in the example message be

6条回答
  •  佛祖请我去吃肉
    2020-11-28 08:53

    IsBodyHtml = true is undoubtedly the most important part.

    But if you want to provide an email with both a text/plain part and a text/html part composed as alternates, it is also possible using the AlternateView class:

    MailMessage msg = new MailMessage();
    AlternateView plainView = AlternateView
         .CreateAlternateViewFromString("Some plaintext", Encoding.UTF8, "text/plain");
    // We have something to show in real old mail clients.
    msg.AlternateViews.Add(plainView); 
    string htmlText = "The fancy part.";
    AlternateView htmlView = 
         AlternateView.CreateAlternateViewFromString(htmlText, Encoding.UTF8, "text/html");
    msg.AlternateViews.Add(htmlView); // And a html attachment to make sure.
    msg.Body = htmlText;  // But the basis is the html body
    msg.IsBodyHtml = true; // But the basis is the html body
    

提交回复
热议问题