日期:2014-05-17 浏览次数:20826 次
在做一个基于ASP.NET的项目时需要使用html模板发送电子邮件,研究了下,总结如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>HTML Template</title> </head> <body> <p >Dear $USER_NAME$,</p> <p>My name is $NAME$</p> <p >Best Regards,<br /> $MY_NAME$</p> </body> </html>
/// <summary> /// 发送邮件 /// </summary> public void SendEmail(string email_from,string email_to, string email_cc, string userName, string name, string myName) { try { // 建立一个邮件实体 MailAddress from = new MailAddress(email_from); MailAddress to = new MailAddress(email_to); MailMessage message = new MailMessage(from, to); string strbody = ReplaceText(userName, name, myName); if (email_cc.ToString() != string.Empty) { foreach (string ccs in email_cc.Split(';')) { MailAddress cc = new MailAddress(ccs); message.CC.Add(cc); } } message.IsBodyHtml = true; message.BodyEncoding = System.Text.Encoding.UTF8; message.Priority = MailPriority.High; message.Body = strbody; message.Subject = "Subject"; SmtpClient smtp = new SmtpClient(); smtp.Host = Configuration.MailHost; smtp.Port = Configuration.MailHostPort; smtp.Credentials = new System.Net.NetworkCredential(email_from, "emailpassword"); smtp.Send(message); } catch (Exception ex) { throw ex; } }
/// <summary> ///替换模板中的字段值 /// </summary> public string ReplaceText(String userName,string name,string myName) { string path = string.Empty; path = HttpContext.Current.Server.MapPath("Email_Template\\email.html"); if (path == string.Empty) { return string.Empty; } System.IO.StreamReader sr = new System.IO.StreamReader(path); string str = string.Empty; str = sr.ReadToEnd(); str = str.Replace("$USER_NAME$", userName); str = str.Replace("$NAME$", name); str = str.Replace("$MY_NAME$",myName); return str; }