在网站中可能经常需要给用户发送邮件,而给不同的用户发送的邮件内容,除了部分内容不一样外,大部分内容可能是相同的,这就需要按模板发送邮件。基本思想就是先定义一个邮件模板,在邮件模板中定义要替换的字符串,然后通过使用正则表达式查找并进行替换。下面讲讲具体的实现方法。
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>忘记密码通知</title>
</head>
<body>
您的账号是:{#AccountName}<br />
您的密码是:{#Password}<br /><br />
{#Date}
</body>
</html>
2.使用正则表达式查找并替换。
public class EmailParam
{
private string _type;
private string _value;
public string Value
{
get { return _value; }
set { _value = value; }
}
public string Type
{
get { return _type; }
set { _type = value; }
}
}
public static void Send(List<EmailParam> listEmailParam)
{
//获取html文件,并读取文件内容
string filePath = AppDomain.CurrentDomain.BaseDirectory + "EmailTemplate/ForgetPassword.htm";
StreamReader sr = new StreamReader(filePath);
string mailContent = sr.ReadToEnd();
//使用正则表单式匹配和替换
Regex regex=new Regex(@"\{#([^\}]*)(\})",RegexOptions.IgnoreCase);
MatchCollection matchResult=regex.Matches(mailContent);
for (int i = 0; i < listEmailParam.Count; i++)
{
for (int j = 0; j < matchResult.Count; j++)
{
if (listEmailParam[i].Type == matchResult[j].Value)
{
mailContent=mailContent.Replace(matchResult[j].Value, listEmailParam[i].Value);
}
}
}
//使用Gamil服务器发送邮件
MailAddress from = new MailAddress("***@gmail.com", "发件人名称");
MailAddress to = new MailAddress("***@163.com", "收件人名称");
MailMessage mailMessage = new MailMessage(from, to);
mailMessage.Body = mailContent;
mailMessage.Subject = "忘记用户名和密码";
mailMessage.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Credentials = new NetworkCredential("***@gmail.com", "密码");
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Send(mailMessage);
}
List<EmailParam> listEmailParam = new List<EmailParam>();
EmailParam param1 = new EmailParam();
param1.Type = "{#AccountName}";
param1.Value = "admin";
listEmailParam.Add(param1);
EmailParam param2 = new EmailParam();
param2.Type = "{#Password}";
param2.Value = "123456";
listEmailParam.Add(param2);
EmailParam param3 = new EmailParam();
param3.Type = "{#Date}";
param3.Value = DateTime.Now.ToShortDateString();
listEmailParam.Add(param3);
EmailHelper.Send(listEmailParam);