本文实例讲述了C#.NET采用HTML模板发送电子邮件的方法,是非常实用的技巧。分享给大家供大家参考。具体方法如下:
要使用html模板进行发送邮件,需要准备以下几项工作:
1)HTML模板
2)替换函数(替换模板中绑定的变量)
3)邮件函数(发送邮件)
一、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 Report</title> </head> <body> <p>$USER_NAME$:</p> <p>My name is $NAME$</p> <p >This is a Test Email,<br /> $MY_NAME$</p> </body> </html>
其中USER_NAME、NAME、MY_NAME这三个变量用$符号包裹进行标识,是需要被替换的字符串,它会在下面的替换函数中被动态替换。
二、替换函数
/// <summary> ///替换模板中的字段值 /// </summary> public string ReplaceText(String userName,string name,string myName) { string path = string.Empty; path = HttpContext.Current.Server.MapPath("EmailTemplate//emailTemplate.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; }
三、邮件发送
/// <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; //邮件BODY内容 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; } }
其实无论采取什么方式或组件进行邮件发送,要替换HTML模板中的内容,只需一个Replace函数即可。
相信本文所述对大家C#.net程序设计的学习有一定的借鉴价值。
新闻热点
疑难解答