本文實(shí)例講述了C#.NET采用HTML模板發(fā)送電子郵件的方法,是非常實(shí)用的技巧。分享給大家供大家參考。具體方法如下:
要使用html模板進(jìn)行發(fā)送郵件,需要準(zhǔn)備以下幾項(xiàng)工作:
1)HTML模板
2)替換函數(shù)(替換模板中綁定的變量)
3)郵件函數(shù)(發(fā)送郵件)
一、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這三個(gè)變量用$符號(hào)包裹進(jìn)行標(biāo)識(shí),是需要被替換的字符串,它會(huì)在下面的替換函數(shù)中被動(dòng)態(tài)替換。
二、替換函數(shù)
/// <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; } 三、郵件發(fā)送
/// <summary> /// 發(fā)送郵件 /// </summary> public void SendEmail(string email_from,string email_to, string email_cc, string userName, string name, string myName) { try { // 建立一個(gè)郵件實(shí)體 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內(nèi)容 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); //發(fā)送郵件 } catch (Exception ex) { throw ex; } }其實(shí)無論采取什么方式或組件進(jìn)行郵件發(fā)送,要替換HTML模板中的內(nèi)容,只需一個(gè)Replace函數(shù)即可。
相信本文所述對(duì)大家C#.net程序設(shè)計(jì)的學(xué)習(xí)有一定的借鑒價(jià)值。
新聞熱點(diǎn)
疑難解答
圖片精選