我想通过asp.net发送电子邮件。我使用这段代码,工作正常。
mail.From = new MailAddress("mail@gmail.com", "sender", System.Text.Encoding.UTF8);
string to = Session["Umail"].ToString();
mail.To.Add(to);
mail.IsBodyHtml = true;
mail.SubjectEncoding = Encoding.UTF8;
mail.BodyEncoding = Encoding.GetEncoding("utf-8");
mail.Subject = "subject";
mail.Body = "body" ;
SmtpClient smtp = new SmtpClient("Smtp.gmail.Com", 587);
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("mail@gmail.com", "pass"); smtp.Send(mail);
但我想要一份定制而美丽的邮件。就像从Facebook,谷歌团队等发送的电子邮件一样。我知道可以在mail.Body
中使用html标签,但这是好方法吗?什么是最好的方式?
答案 0 :(得分:4)
这已准备好使用我用于发送包含文本内容和基于html模板的内容的电子邮件的代码段:
// first we create a plain text version and set it to the AlternateView
// then we create the HTML version
MailMessage msg = new MailMessage();
msg.From = new MailAddress("from@email", "From Name");
msg.Subject = "Subject";
msg.To.Add("to@email");
msg.BodyEncoding = Encoding.UTF8;
String plainBody = "Body of plain email";
//first we create the text version
AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainBody, Encoding.UTF8, "text/plain");
msg.AlternateViews.Add(plainView);
//now create the HTML version
MailDefinition message = new MailDefinition();
message.BodyFileName = "~/MailTemplates/template1.htm";
message.IsBodyHtml = true;
message.From = "from@email";
message.Subject = "Subject";
//Build replacement collection to replace fields in template1.htm file
ListDictionary replacements = new ListDictionary();
replacements.Add("<%USERNAME%>", "ToUsername");//example of dynamic content for Username
//now create mail message using the mail definition object
//the CreateMailMessage object takes a source control object as the last parameter,
//if the object you are working with is webcontrol then you can just pass "this",
//otherwise create a dummy control as below.
MailMessage msgHtml = message.CreateMailMessage("to@email", replacements, new LiteralControl());
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(msgHtml.Body, Encoding.UTF8, "text/html");
//example of a linked image
LinkedResource imgRes = new LinkedResource(Server.MapPath("~/MailTemplates/images/imgA.jpg"), System.Net.Mime.MediaTypeNames.Image.Jpeg);
imgRes.ContentId = "imgA";
imgRes.ContentType.Name = "imgA.jpg";
imgRes.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
htmlView.LinkedResources.Add(imgRes);
msg.AlternateViews.Add(htmlView);
//sending prepared email
SmtpClient smtp = new SmtpClient();//It reads the SMPT params from Web.config
smtp.Send(msg);
这些是html模板的关键部分:
<p>Username: <%USERNAME%></p>
<img src="cid:imgA"/>
答案 1 :(得分:1)
我喜欢定制的漂亮邮件。
我知道可以在
mail.Body
中使用html标签,但这是好方法吗?什么是 最好的方法?
我不知道完全这是什么意思,但一般来说,有两种方法可以做到。 (如果我们谈论电子邮件中的图像或来源等。)
您可以使用LinkedResource
类.NET Framework。
表示电子邮件附件中的嵌入式外部资源,例如 作为HTML附件中的图像。
或者,更简单地说,在我看来,如果您想在电子邮件中使用某些图片,请将图片放在公共位置,然后在电子邮件的HTML中引用该位置。< / p>