如何在C#中发送多部分MIME消息?

22

我希望发送多部分MIME消息,其中包含HTML组件和普通文本组件,以供那些无法处理HTML的电子邮件客户端的用户使用。然而,System.Net.Mail.MailMessage类似乎不支持此功能。您该如何实现?

1个回答

42

唉,这真的很简单...但我会把答案留在这里,供像我一样在SO上寻找答案之前先谷歌的人使用... :)

感谢这篇文章

使用AlternateViews,就像这样:

//create the mail message
var mail = new MailMessage();

//set the addresses
mail.From = new MailAddress("me@mycompany.com");
mail.To.Add("you@yourcompany.com");

//set the content
mail.Subject = "This is an email";

//first we create the Plain Text part
var plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");
//then we create the Html part
var htmlView = AlternateView.CreateAlternateViewFromString("<b>this is bold text, and viewable by those mail clients that support html</b>", null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);

//send the message
var smtp = new SmtpClient("127.0.0.1"); //specify the mail server address
smtp.Send(mail);

8
如果您想要一个类型更强的系统,您可以使用MediaTypeNames.Text.Plain或者MediaTypeNames.Text.Html代替"text/plain"和"text/html"。 - Talon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接