注意的地方
1. MailMessage email = new MailMessage(); //实例化邮件对象
email.Subject = dt.Rows[0]["THEME"].ToString().Replace('\r', ' ').Replace('\n', ' ');//主题里面这些东西报错
邮件主题有时候我们的输入框是可以换行的,就会有换行符,邮件协议里面的主题是不允许有这些"\r,\n",需要过滤掉.
2.添加密送 邮件地址的时候要正确的邮箱地址,不然也会抛出异常, email.Bcc.Add("邮件地址");//密送 ,例如这个邮箱地址就不对"xiao.h.x.@163.com", x.@这中间有一个点,不符合邮件地址格式
3.邮件发送的图片的内容,如果是插入图片的链接的时候,最好是给图片设置一个宽度,在outLOOK 里面图片宽度超过了一定长度就显示不出来,大慨设置为"900",不然发送的图片,用OUTLOOK 打开看不到.
/// <summary>
/// 发送邮件
/// </summary>
private static void SendEmail(Task task)
{
//定义失败明细数
int failedcount = 0;
int emailFailedCount = 0;
//获取邮件
DataTable dt = Dao.GetDataTable(string.Format(Config.Sql_strGetEmail, task.TaskId));
if (dt.Rows.Count == 0) return;
#region 初始化邮件
MailMessage email = new MailMessage();
//实例化邮件对象
try
{
email.Subject = dt.Rows[0]["THEME"].ToString().Replace('\r', ' ').Replace('\n', ' ');//主题里面这些东西报错.
email.Body = dt.Rows[0]["ECONTENT"].ToString();
email.IsBodyHtml = true;
}
catch(Exception exce)
{
Log.WriteLog_Email(string.Format("邮件初始化失败!原因:{0}", exce.Message));
return;
}
#endregion
#region 附件
//创建任务附件文件夹
if (!Directory.Exists("Attachments"))
Directory.CreateDirectory("Attachments");
if (!Directory.Exists(string.Format(@"Attachments\{0}", task.TaskId)))
Directory.CreateDirectory(string.Format(@"Attachments\{0}", task.TaskId));
//获取附件
DataTable attachments = Dao.GetDataTable(string.Format(Config.Sql_strGetAttachmentsByTaskId, task.TaskId));
//遍历附件
if (attachments.Rows.Count > 0)
{
Attachment attachment = null;
string filename;
foreach (DataRow row in attachments.Rows)
{
filename = string.Format(@"Attachments\{0}\{1}", task.TaskId, row["FILENAME"].ToString());
try
{
File.WriteAllBytes(filename, (byte[])row["CONTENT"]);
}
catch (Exception ex)
{
//Log.WriteLog(string.Format("附件下载异常:{0}", ex.Message));
}
attachment = new Attachment(filename);
email.Attachments.Add(attachment);
}
}
#endregion
#region 根据登录的邮箱查找对应的验证用户和密码
//邮箱的登录帐号
string loginName = dt.Rows[0]["SENDNAME"].ToString();
string loginPwd = dt.Rows[0]["PASSWORD"].ToString();
DataTable emailLoginIdDT = Dao.GetDataTable(string.Format(Config.SQL_strEmailLoginId, dt.Rows[0]["SENDNAME"].ToString()));
if (emailLoginIdDT.Rows.Count>0)
{
loginName = emailLoginIdDT.Rows[0]["ACCOUNT"].ToString();
loginPwd = emailLoginIdDT.Rows[0]["PASSWORD"].ToString();
}
#endregion
#region 初始化发送对象
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
switch (Config.AppState)
{
default:
break;
case AppState.Local:
email.From = new MailAddress(Config.LEmailAccount);
client.Host = Config.LSmtp;
client.Port = Config.LMailPort;
client.Credentials = new System.Net.NetworkCredential(Config.LEmailAccount, Config.LEmailPwd);
break;
case AppState.Dev:
case AppState.Test:
case AppState.Production:
try
{
email.From = new MailAddress(dt.Rows[0]["SENDNAME"].ToString());
client.Host = Config.RSmtp;
client.Port = Config.RMailPort;
client.Credentials = new System.Net.NetworkCredential(loginName, loginPwd);
}
catch(Exception exx)
{
Log.WriteLog_Email(string.Format("邮件初始化失败!原因:{0}", exx.Message));
return;
}
break;
}
client.DeliveryMethod = SmtpDeliveryMethod.Network;
#endregion
#region 遍历发送
//修改地方 by andy 2012-05-11
#region 修改取数据
List<ITaskDetail> tempDetails = new List<ITaskDetail>();
string strDetail = Config.Sql_strDetail;
DataTable dtDetail = new DataTable();
OracleConnection conn = new OracleConnection();
conn.ConnectionString = Config.DbConnectionString;
OracleCommand comm = conn.CreateCommand();
OracleDataAdapter adapter = new OracleDataAdapter(comm);
try
{
conn.Open();
comm.CommandText = strDetail;
adapter.Fill(dtDetail);
Log.WriteLog_Email("数据加载成功!");
}
catch (Exception ex)
{
Log.WriteLog_Email(string.Format("数据加载失败!原因:{0}", ex.Message));
}
finally
{
conn.Close();
}
string detailid;
string taskid;
int sstate;
string tag;
foreach (DataRow row in dtDetail.Rows)
{
detailid = Convert.ToString(row["DETAILID"]);
taskid = Convert.ToString(row["TASKID"]);
sstate = Convert.ToInt32(row["SENDSTATE"]);
tag = Convert.ToString(row["TAG"]);
tempDetails.Add(new ITaskDetail(detailid, taskid, sstate, tag));
}
//过滤获取这个任务的ID
List<ITaskDetail> details = new List<ITaskDetail>();
IEnumerable<ITaskDetail> tds = from detail in tempDetails
where detail.TaskId == task.TaskId
select detail;
foreach (ITaskDetail tempdl in tds)
{
details.Add(tempdl);
}
#endregion
// foreach (ITaskDetail detail in task.Details)
foreach (ITaskDetail detail in details)
{
if (detail.Sendstate == SendState.Success) continue;
email.Bcc.Clear();
if (string.IsNullOrEmpty(detail.Tag))
{
Log.WriteLog_Email(string.Format("邮件明细{0}跳过发送,因为没有邮件地址!", detail.DetailId));
continue;
}
try
{
email.Bcc.Add(detail.Tag);//密送
}
catch(Exception ec)
{
Log.WriteLog_Email(string.Format("邮件地址不正确 {0} 添加密送失败 !", detail.Tag));
emailFailedCount++; //邮件地址不对的
detail.Sendstate = SendState.Fail;
Log.WriteLog_Email(string.Format("邮件明细{0}({1})发送失败,原因{2}", detail.DetailId, detail.Tag, ec.InnerException == null ? ec.Message : ec.InnerException.Message));
Dao.ExecuteSql(string.Format(Config.Sql_strSendEmailFail, detail.DetailId));
Dao.ExecuteSql(string.Format(Config.Sql_strUpdateDetail, (int)detail.Sendstate, detail.Tag, detail.DetailId));
continue;
}
try
{
client.Send(email);
detail.Sendstate = SendState.Success;
Log.WriteLog_Email(string.Format("邮件明细{0}({1})发送成功!", detail.DetailId, detail.Tag));
Dao.ExecuteSql(string.Format(Config.Sql_strSendEmailSucess, detail.DetailId));
}
catch (Exception ex)
{
detail.Sendstate = SendState.Fail;
failedcount++;
Log.WriteLog_Email(string.Format("邮件明细{0}({1})发送失败,原因{2}", detail.DetailId, detail.Tag, ex.InnerException == null ? ex.Message : ex.InnerException.Message));
Dao.ExecuteSql(string.Format(Config.Sql_strSendEmailFail, detail.DetailId));
}
finally
{
Dao.ExecuteSql(string.Format(Config.Sql_strUpdateDetail, (int)detail.Sendstate, detail.Tag, detail.DetailId));
}
}
#endregion
#region 状态处理
Log.WriteLog_Email(string.Format("邮件任务{0}第{3}次发送完毕,总共{1}封,失败{2}封", task.TaskId, details.Count, failedcount > 0 ? failedcount : emailFailedCount, task.SendTimes));
task.Taskstate = failedcount == 0 ? TaskState.Executed : TaskState.Nonexecution;
task.UpdateState();
#endregion
}