这是我每天使用的SMTP帮助器的摘录….
public bool SendMail(string strTo, string strFrom, string strCc, string strBcc, string strBody, string strSubject)
{
bool isComplete = true;
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
try
{
//Default port will be 25
smtpClient.Port = 25;
message.From = new MailAddress(smtpEmailSource);
message.To.Add(strTo);
message.Subject = strSubject;
if (strCc != "") { message.Bcc.Add(new MailAddress(strCc)); }
if (strBcc != "") { message.Bcc.Add(new MailAddress(strBcc)); }
message.IsBodyHtml = true;
string html = strBody; //I usually use .HTML files with tags (e.g. {firstName}) I replace with content. This allows me to edit the emails in VS by opening a .HTML file and it's easy to do string replacements.
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(html, new ContentType("text/html"));
message.AlternateViews.Add(htmlView);
// Send SMTP mail
smtpClient.Send(message);
}
catch
{
isComplete = false;
}
return isComplete;
}
[UPDATE]
关键点,我最初离开了…
> IsBodyHtml声明您的邮件是HTML格式的.如果你只发送一个HTML视图,这就是你需要的.
> AlternateView用于存储我的HTML,这不是发送HTML消息所必需的,但如果要发送包含HTML和纯文本的消息(如果接收方无法呈现HTML),则需要此功能.
我拿出了我以上的plainView,这不是很明显,对不起…
这里的关键是,如果要发送HTML格式的消息,您需要使用IsBodyHtml = true(默认为false)将您的内容呈现为HTML.