使用SmtpClient通过C#发送HTML电子邮件

46 c# asp.net email smtpclient

如何发送HTML电子邮件?我使用此答案中的代码发送电子邮件SmtpClient,但它们始终是纯文本,因此下面示例消息中的链接不是这样格式化的.

<p>Welcome to SiteName. To activate your account, visit this URL: <a href="http://SiteName.com/a?key=1234">http://SiteName.com/a?key=1234</a>.</p>
Run Code Online (Sandbox Code Playgroud)

如何在我发送的电子邮件中启用HTML?

小智 93

这就是我做的:

MailMessage mail = new MailMessage(from, to, subject, message);
mail.IsBodyHtml = true;
SmtpClient client = new SmtpClient("localhost");
client.Send(mail);
Run Code Online (Sandbox Code Playgroud)

请注意,我将邮件消息html设置为true: mail.IsBodyHtml = true;

  • 值得注意的是,"MailMessage"和"SmtpClient"都实现了"IDisposable",需要进行相应的处理. (6认同)

Rop*_*tah 19

我相信它是这样的:

mailObject.IsBodyHtml = true;
Run Code Online (Sandbox Code Playgroud)


fae*_*ter 16

IsBodyHtml = true 无疑是最重要的部分.

但是如果你想提供一个同时包含text/plain部分和text/html部分作为替换的电子邮件,也可以使用AlternateView该类:

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 <b>fancy</b> 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
Run Code Online (Sandbox Code Playgroud)

  • 它不仅是必要的,而且很重要的是它被添加到普通的替代视图之后。请参阅 http://stackoverflow.com/questions/5188605/gmail-displays-plain-text-email-instead-html。但是,如果您添加了 html 替代视图,则无需指定 Body 和 IsBodyHtml。 (2认同)

Bdi*_*iem 8

应用Mailbody的正确编码.

mail.IsBodyHtml = true;
Run Code Online (Sandbox Code Playgroud)