asp.net-使用SmtpClien通过C#发送HTML电子邮件
如何发送HTML电子邮件? 我使用此答案中的代码发送带有2947892219308678672000的电子邮件,但它们始终是纯文本格式,因此以下示例消息中的链接未这样格式化。
Welcome to SiteName. To activate your account, visit this URL: http://SiteName.com/a?key=1234.
如何在发送的电子邮件中启用HTML?
6个解决方案
91 votes
这是我的工作:
MailMessage mail = new MailMessage(from, to, subject, message);
mail.IsBodyHtml = true;
SmtpClient client = new SmtpClient("localhost");
client.Send(mail);
请注意,我将邮件html设置为true:mail.IsBodyHtml = true;
Josiah Peters answered 2020-07-01T23:23:16Z
18 votes
我相信这是这样的:
mailObject.IsBodyHtml = true;
Ropstah answered 2020-07-01T23:23:35Z
16 votes
IsBodyHtml = true无疑是最重要的部分。
但是,如果要提供包含文本/纯文本部分和文本/ 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 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
faester answered 2020-07-01T23:24:00Z
8 votes
应用电子邮件正文的正确编码。
mail.IsBodyHtml = true;
Bdiem answered 2020-07-01T23:24:20Z
1 votes
我有一个主意,您可以在项目中添加一个复选框,以将HTML作为电子邮件发送给用户,并添加以下代码以启用它:
MailMessage mail = new MailMessage(from, to, subject, message);
if(checkBox1.CheckState == CheckState.Checked )
{
mail.IsBodyHtml = true;
}
SmtpClient client = new SmtpClient("localhost");
client.Send(mail);
nassimlouchani answered 2020-07-01T23:24:40Z
0 votes
如果您使用的是Mailkit,我们可以将TextBody,HtmlBody和Both用作邮件正文。 只需编写此代码。 会帮你的
MimeMessage mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress(senderName, sender@address.com));
mailMessage.Sender = new MailboxAddress(senderName, sender@address.com);
mailMessage.To.Add(new MailboxAddress(emailid, emailid));
mailMessage.Subject = subject;
mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
mailMessage.Subject = subject;
var builder = new BodyBuilder();
builder.HtmlBody = "Hello There";
try
{
using (var smtpClient = new SmtpClient())
{
smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
smtpClient.Authenticate("user@name.com", "password");
smtpClient.Send(mailMessage);
Console.WriteLine("Success");
}
}
catch (SmtpCommandException ex)
{
Console.WriteLine(ex.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Jairath answered 2020-07-01T23:25:00Z