呼之欲出 WebMail 开发手记 (七) 邮件发送
注意事项:
1.用户需要设置当前默认的邮件发送服务器
2.如果用户选择邮件发送级别为高级,就应当立即发送
3.设置邮件编码格式
与收邮件相比,发邮件就相对要简单一些。
首先、用户需要设置当前默认的发送邮箱服务器(从邮箱设置中选择一个),这样方便自动提交呢称和对方需要回复邮件时的回复地址等。当然发送邮件的时候我们还可以设置邮件模板,比如业务员自己的相关联系,电话号码,地址等等。这些只是页面的东西,这次还是讲多线程发送邮件。
第二、发邮件的时候,如果用户选择邮件发送级别为高级,就应当立即发送(要不然,延务了用户的时间可不要找我哦~~),其他的才可以暂时放到线程里面,由服务器自动处理。
SendStart:SendStop:BeginSend
发送邮件#region 发送邮件
public void SendStart() {
if (userId == 0 || _threadSend != null)
return;
lock(this) {
if(_smtpState != 0) {
_smtpState = 0;
}
_threadSend = new Thread(new ThreadStart(BeginSend));
_threadSend.Start();
}
}
public void SendStop() {
if (_threadSend != null) {
_threadSend.Abort();
_threadSend = null;
}
}
private void BeginSend() {
SqlDataReader configs = (new Config()).GetConfigs(userId);
if(configs != null) {
_smtpTime = DateTime.Now;
_smtpState = 1;
while(configs.Read()) {
DateTime pTime = DateTime.Parse(configs["smtpTime"].ToString());
TimeSpan m = DateTime.Now - pTime;
// 每10分钟发送邮件一次/超过100分钟也重新发送
if ((m.TotalMinutes >= 10 && configs["smtpDoing"].ToString() == "0") || m.TotalMinutes >= 100) {
_smtpMail = string.Format("当前发送邮箱({0}):", configs["ConfigName"]);
dbmail.SetSendState(userId, configs["Id"], DateTime.Now, 1);
Send(
int.Parse(configs["ID"].ToString()),
configs["SmtpUid"].ToString(),
MailHelper.Decrypt(configs["SmtpPwd"].ToString(), "123456"),
configs["SmtpAddress"].ToString(),
int.Parse(configs["SmtpPort"].ToString()),
byte.Parse(configs["SmtpAuth"].ToString()),
configs["SmtpReply"].ToString(),
configs["SmtpName"].ToString()
);
}
}
configs.Close();
_smtpState = 2;
_smtpMessage = "发送完成";
} else {
_smtpState = 3;
_smtpMessage = "无配置信息";
}
_threadSend = null;
}
#endregion
发送邮件#region 发送邮件
public void SendStart() {
if (userId == 0 || _threadSend != null)
return;
lock(this) {
if(_smtpState != 0) {
_smtpState = 0;
}
_threadSend = new Thread(new ThreadStart(BeginSend));
_threadSend.Start();
}
}
public void SendStop() {
if (_threadSend != null) {
_threadSend.Abort();
_threadSend = null;
}
}
private void BeginSend() {
SqlDataReader configs = (new Config()).GetConfigs(userId);
if(configs != null) {
_smtpTime = DateTime.Now;
_smtpState = 1;
while(configs.Read()) {
DateTime pTime = DateTime.Parse(configs["smtpTime"].ToString());
TimeSpan m = DateTime.Now - pTime;
// 每10分钟发送邮件一次/超过100分钟也重新发送
if ((m.TotalMinutes >= 10 && configs["smtpDoing"].ToString() == "0") || m.TotalMinutes >= 100) {
_smtpMail = string.Format("当前发送邮箱({0}):", configs["ConfigName"]);
dbmail.SetSendState(userId, configs["Id"], DateTime.Now, 1);
Send(
int.Parse(configs["ID"].ToString()),
configs["SmtpUid"].ToString(),
MailHelper.Decrypt(configs["SmtpPwd"].ToString(), "123456"),
configs["SmtpAddress"].ToString(),
int.Parse(configs["SmtpPort"].ToString()),
byte.Parse(configs["SmtpAuth"].ToString()),
configs["SmtpReply"].ToString(),
configs["SmtpName"].ToString()
);
}
}
configs.Close();
_smtpState = 2;
_smtpMessage = "发送完成";
} else {
_smtpState = 3;
_smtpMessage = "无配置信息";
}
_threadSend = null;
}
#endregion
发送邮件我们使用 System.Net.Mail 下面的 MailMessage 类,记住一定要设置邮件主题、内容、附件等的编码,一般我们设置 gb2312 就可以了,当然也可以使用 utf-8 可能会更好:
Send:发送单个邮箱的邮件
发送单个邮箱的邮件#region 发送单个邮箱的邮件
/**//// <summary>
/// 发送单个邮箱的邮件
/// </summary>
public void Send(int configId, string smtpUid, string smtpPwd, string smtpAddress, int smtpPort, byte smtpAuth, string smtpReply, string smtpName) {
if(!string.IsNullOrEmpty(smtpAddress)) {
MailHelper.SaveLogs(basePath, _smtpMail);//string.Format("开始发送 {0} 的邮件, 当前用户ID是 {1}", _smtpMail, userId));
_smtpMessage = "正在检查需要发送的邮件";
DataSet mails = dbmail.GetNeedSendMailsByConfigDS(configId);
if(mails.Tables.Count > 0) {
int mSize = 0;
MailMessage mail;
MailAddressCollection mailAddr;
Attachment attachment;
// 邮件编码
System.Text.Encoding enc = System.Text.Encoding.GetEncoding("gb2312");
// 发送组件基本配置
SmtpClient client = new SmtpClient(smtpAddress, smtpPort);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
if(smtpAuth == 1) {
client.UseDefaultCredentials = true;
client.Credentials = new System.Net.NetworkCredential(smtpUid, smtpPwd);
}
// 依次发送邮件
for(int i = 0; i < mails.Tables[0].Rows.Count; i++) {
_smtpMessage = string.Format("正在发送第 {0} 封邮件,共 {1} 封", i+1, mails.Tables[0].Rows.Count);
DataRow mymail = mails.Tables[0].Rows[i];
try {
mail = new MailMessage();
mail.From = new MailAddress(smtpReply, smtpName);
// 设置优先级别
switch(mymail["Priority"].ToString()) {
case "0":
mail.Priority = MailPriority.Low;
break;
case "2":
mail.Priority = MailPriority.High;
break;
case "1":
default:
mail.Priority = MailPriority.Normal;
break;
}
mailAddr = MailHelper.GetAddress(mymail["ToAddress"].ToString(), ref mSize);
foreach(MailAddress address in mailAddr) {
mail.To.Add(address);
}
mailAddr = MailHelper.GetAddress(mymail["CCAddress"].ToString(), ref mSize);
foreach(MailAddress address in mailAddr) {
mail.CC.Add(address);
}
mail.Subject = mymail["Name"].ToString();
mail.SubjectEncoding = enc;
mail.IsBodyHtml = true;
mail.Body = mymail["Body"].ToString();
mail.BodyEncoding = enc;
// 添加附件
SqlDataReader dr = dbmail.GetAttachmentsByMail(int.Parse(mymail["ID"].ToString()));
if(dr != null) {
while(dr.Read()) {
attachment = new Attachment(basePath + dr["URL"].ToString());
attachment.Name = dr["Name"].ToString();
attachment.NameEncoding = enc;
mail.Attachments.Add(attachment);
}
}
client.Send(mail);
// 设置发送状态
dbmail.SetSendState(int.Parse(mymail["ID"].ToString()));
} catch(Exception ex) {
MailHelper.SaveLogs(basePath, "发送第" + i.ToString() + "封邮件时出错:" + ex.Message);
}
}
mails.Dispose();
}
// 保存最后发送时间
dbmail.SetSendState(userId, configId, DateTime.Now, 0);
MailHelper.SaveLogs(basePath, "邮件发送完成\r\n");
}
}
#endregion
发送单个邮箱的邮件#region 发送单个邮箱的邮件
/**//// <summary>
/// 发送单个邮箱的邮件
/// </summary>
public void Send(int configId, string smtpUid, string smtpPwd, string smtpAddress, int smtpPort, byte smtpAuth, string smtpReply, string smtpName) {
if(!string.IsNullOrEmpty(smtpAddress)) {
MailHelper.SaveLogs(basePath, _smtpMail);//string.Format("开始发送 {0} 的邮件, 当前用户ID是 {1}", _smtpMail, userId));
_smtpMessage = "正在检查需要发送的邮件";
DataSet mails = dbmail.GetNeedSendMailsByConfigDS(configId);
if(mails.Tables.Count > 0) {
int mSize = 0;
MailMessage mail;
MailAddressCollection mailAddr;
Attachment attachment;
// 邮件编码
System.Text.Encoding enc = System.Text.Encoding.GetEncoding("gb2312");
// 发送组件基本配置
SmtpClient client = new SmtpClient(smtpAddress, smtpPort);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
if(smtpAuth == 1) {
client.UseDefaultCredentials = true;
client.Credentials = new System.Net.NetworkCredential(smtpUid, smtpPwd);
}
// 依次发送邮件
for(int i = 0; i < mails.Tables[0].Rows.Count; i++) {
_smtpMessage = string.Format("正在发送第 {0} 封邮件,共 {1} 封", i+1, mails.Tables[0].Rows.Count);
DataRow mymail = mails.Tables[0].Rows[i];
try {
mail = new MailMessage();
mail.From = new MailAddress(smtpReply, smtpName);
// 设置优先级别
switch(mymail["Priority"].ToString()) {
case "0":
mail.Priority = MailPriority.Low;
break;
case "2":
mail.Priority = MailPriority.High;
break;
case "1":
default:
mail.Priority = MailPriority.Normal;
break;
}
mailAddr = MailHelper.GetAddress(mymail["ToAddress"].ToString(), ref mSize);
foreach(MailAddress address in mailAddr) {
mail.To.Add(address);
}
mailAddr = MailHelper.GetAddress(mymail["CCAddress"].ToString(), ref mSize);
foreach(MailAddress address in mailAddr) {
mail.CC.Add(address);
}
mail.Subject = mymail["Name"].ToString();
mail.SubjectEncoding = enc;
mail.IsBodyHtml = true;
mail.Body = mymail["Body"].ToString();
mail.BodyEncoding = enc;
// 添加附件
SqlDataReader dr = dbmail.GetAttachmentsByMail(int.Parse(mymail["ID"].ToString()));
if(dr != null) {
while(dr.Read()) {
attachment = new Attachment(basePath + dr["URL"].ToString());
attachment.Name = dr["Name"].ToString();
attachment.NameEncoding = enc;
mail.Attachments.Add(attachment);
}
}
client.Send(mail);
// 设置发送状态
dbmail.SetSendState(int.Parse(mymail["ID"].ToString()));
} catch(Exception ex) {
MailHelper.SaveLogs(basePath, "发送第" + i.ToString() + "封邮件时出错:" + ex.Message);
}
}
mails.Dispose();
}
// 保存最后发送时间
dbmail.SetSendState(userId, configId, DateTime.Now, 0);
MailHelper.SaveLogs(basePath, "邮件发送完成\r\n");
}
}
#endregion