C#.NET采取HTML模板發送電子郵件完全實例。本站提示廣大學習愛好者:(C#.NET采取HTML模板發送電子郵件完全實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#.NET采取HTML模板發送電子郵件完全實例正文
本文實例講述了C#.NET采取HTML模板發送電子郵件的辦法,長短常適用的技能。分享給年夜家供年夜家參考。詳細辦法以下:
要應用html模板停止發送郵件,須要預備以下幾項任務:
1)HTML模板
2)調換函數(調換模板中綁定的變量)
3)郵件函數(發送郵件)
1、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這三個變量用$符號包裹停止標識,是須要被調換的字符串,它會鄙人面的調換函數中主動態調換。
2、調換函數
/// <summary> ///調換模板中的字段值 /// </summary> public string WordStrText(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.WordStr("$USER_NAME$", userName); str = str.WordStr("$NAME$", name); str = str.WordStr("$MY_NAME$",myName); return str; }
3、郵件發送
/// <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 = WordStrText(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模板中的內容,只需一個WordStr函數便可。
信任本文所述對年夜家C#.net法式設計的進修有必定的自創價值。