• 注册
当前位置:1313e > html >正文

C#.NET使用HTML模板发送电子邮件

要使用html模板进行发送邮件,需要准备以下几项工作:

1)HTML模板

2)替换函数(替换模板中绑定的变量)

3)邮件函数(发送邮件)

一、HTML模板

01.  
02.  
03.  
04.    HTML Report  
05.  
06.  
07.

$USER_NAME$:

08. 09. 10.

My name is $NAME$

11.

This is a Test Email,
12. $MY_NAME$

13. 14.


其中USER_NAME、NAME、MY_NAME这三个变量用$符号包裹进行标识,是需要被替换的字符串,它会在下面的替换函数中被动态替换。

二、替换函数

01.///    
02.///替换模板中的字段值   
03.///    
04.public string ReplaceText(String userName,string name,string myName)  
05.{  
06.  
07.    string path = string.Empty;  
08.   
09.    path = HttpContext.Current.Server.MapPath("EmailTemplate\\emailTemplate.html");  
10.             
11.    if (path == string.Empty)  
12.    {  
13.        return string.Empty;  
14.    }  
15.    System.IO.StreamReader sr = new System.IO.StreamReader(path);  
16.    string str = string.Empty;  
17.    str = sr.ReadToEnd();  
18.    str = str.Replace("$USER_NAME$", userName);  
19.    str = str.Replace("$NAME$", name);  
20.    str = str.Replace("$MY_NAME$",myName);  
21.  
22.    return str;  
23.} 

三、邮件发送

01.        ///    
02.        /// 发送邮件   
03.        ///    
04. public void SendEmail(string email_from,string email_to, string email_cc, string userName, string name, string myName)  
05.        {  
06.  
07.            try  
08.            {  
09.                // 建立一个邮件实体   
10.                MailAddress from = new MailAddress(email_from);  
11.  
12.  
13.                MailAddress to = new MailAddress(email_to);  
14.                MailMessage message = new MailMessage(from, to);  
15.  
16.                string strbody = ReplaceText(userName, name, myName);  
17.  
18.                if (email_cc.ToString() != string.Empty)  
19.                {  
20.                    foreach (string ccs in email_cc.Split(';'))  
21.                    {  
22.                        MailAddress cc = new MailAddress(ccs);  
23.                        message.CC.Add(cc);  
24.                    }  
25.                }  
26.  
27.                message.IsBodyHtml = true;  
28.                message.BodyEncoding = System.Text.Encoding.UTF8;  
29.                message.Priority = MailPriority.High;  
30.                message.Body = strbody;  //邮件BODY内容  
31.                message.Subject = "Subject";  
32.  
33.                SmtpClient smtp = new SmtpClient();  
34.                smtp.Host = Configuration.MailHost;  
35.                smtp.Port = Configuration.MailHostPort;  
36.                smtp.Credentials = new System.Net.NetworkCredential(email_from, "emailpassword");  
37.               
38.                smtp.Send(message); //发送邮件  
39.  
40.            } catch (Exception ex)  
41.            {  
42.                throw ex;  
43.            }  
44.  
45.        } 


其实无论采取什么方式或组件进行邮件发送,要替换HTML模板中的内容,只需一个Replace函数即可。

本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 162202241@qq.com 举报,一经查实,本站将立刻删除。

最新评论

欢迎您发表评论:

请登录之后再进行评论

登录