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

Sha*_*ica 20 c# email mime

我想发送多部分MIME消息,其中包含HTML组件和纯文本组件,供电子邮件客户端无法处理HTML的人使用.该System.Net.Mail.MailMessage课似乎不支持这一点.你怎么做呢?

Sha*_*ica 40

噢,这真的很简单......但是我会在这里留下答案给那些像我一样在Googling之前来寻找答案的人...... :)

相信这篇文章.

使用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);
Run Code Online (Sandbox Code Playgroud)

  • 如果你想要一个稍微强一些类型的系统,你可以使用MediaTypeNames.Text.Plain或MediaTypeNames.Text.Html而不是"text/plain"和"text/html" (8认同)