Email 发送
namespace 99999
{
/// <summary>
/// Common interfaces to connect mail server to process e-mail.
/// </summary>
public static class MailClient
{
/// <summary>
/// Process mail queue in database. Call by web service just for schedule process.
/// </summary>
/// <param name="processId"></param>
public static void ProcessQueue( string processId )
{
try
{
//Lock and fetch all mail items in queue.
StringBuilder sqlText = new StringBuilder()
.AppendFormat("UPDATE dbmail_send_task SET MailFrom = '{0}' WHERE Status=0 AND MailFrom IS NULL ", processId)
.AppendFormat("SELECT * FROM dbmail_send_task WHERE Status=0 AND MailFrom ='{0}'", processId); System.Diagnostics.Debug.WriteLine(sqlText.ToString()); DataTable dt = Database.SqlHelper.RunQuery(sqlText.ToString()); string mailServer = AppSettings.MailServer;
if (string.IsNullOrEmpty(mailServer))
{
return;
} foreach (DataRow dr in dt.Rows)
{
int taskId = Convert.ToInt32(dr["TaskID"]); System.Diagnostics.Debug.WriteLine(string.Format("Send item:{0}", taskId)); try
{
//Send mail item using smtp.
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.Subject = Convert.ToString(dr["Title"]);
mail.Body = Convert.ToString(dr["Body"]); //using reply to instead of mail from because of no mail from fields on UI.
string replyTo = Convert.ToString(dr["ReplyTo"]);
if (!string.IsNullOrEmpty(replyTo))
{
mail.Sender = new System.Net.Mail.MailAddress(replyTo);
mail.From = new System.Net.Mail.MailAddress(replyTo);
}
else
{
mail.Sender = new System.Net.Mail.MailAddress(AppSettings.MailDefaultSender);
mail.From = new System.Net.Mail.MailAddress(AppSettings.MailDefaultSender);
} string mailTo = Convert.ToString(dr["MailTo"]);
foreach(string sTemp in mailTo.Split(';'))
{
if (!string.IsNullOrEmpty(sTemp))
{
mail.To.Add(sTemp);
}
} string mailCc = Convert.ToString(dr["MailCc"]);
foreach (string sTemp in mailCc.Split(';'))
{
if (!string.IsNullOrEmpty(sTemp))
{
mail.CC.Add(sTemp);
}
} string mailBcc = Convert.ToString(dr["MailBcc"]);
foreach (string sTemp in mailBcc.Split(';'))
{
if (!string.IsNullOrEmpty(sTemp))
{
mail.Bcc.Add(sTemp);
}
} string attachment = Convert.ToString(dr["Attachments"]);
foreach (string sTemp in attachment.Split(';'))
{
if (!string.IsNullOrEmpty(sTemp))
{
mail.Attachments.Add(new System.Net.Mail.Attachment(sTemp));
}
} mail.IsBodyHtml = true;
mail.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnFailure; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(mailServer);
smtp.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(smtp_SendCompleted);
smtp.SendAsync(mail, taskId);
}
catch (Exception ex)
{
Logging.LogWriter.Write(ex); string sqlText1 = string.Format("UPDATE dbmail_send_task SET [Status]=-1, Remark=N'{0}', SendTime=GETDATE(), MailFrom='ERROR' WHERE TaskID={1} ",ex.Message,taskId);
System.Diagnostics.Debug.WriteLine(sqlText1.ToString());
Database.SqlHelper.RunCommand(sqlText1);
}
}
}
catch (Exception ex)
{
Logging.LogWriter.Write(ex);
}
} /// <summary>
/// Process failed mail queue in database. Call by web service just for schedule process.
/// </summary>
/// <param name="processId"></param>
public static void ResendFailedMails(string processId)
{
try
{
//Lock and fetch all mail items in queue.
StringBuilder sqlText = new StringBuilder()
.AppendFormat("UPDATE dbmail_send_task SET MailFrom = '{0}' WHERE Status=-1 AND MailFrom<>'{0}' AND MailFrom<>'ERROR' ", processId)
.AppendFormat("SELECT * FROM dbmail_send_task WHERE Status=-1 AND MailFrom='{0}' AND MailFrom<>'ERROR' ", processId); System.Diagnostics.Debug.WriteLine(sqlText.ToString()); DataTable dt = Database.SqlHelper.RunQuery(sqlText.ToString()); string mailServer = AppSettings.MailServer;
if (string.IsNullOrEmpty(mailServer))
{
return;
} foreach (DataRow dr in dt.Rows)
{
int taskId = Convert.ToInt32(dr["TaskID"]); System.Diagnostics.Debug.WriteLine(string.Format("Resend item:{0}",taskId)); try
{
//Send mail item using smtp.
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.Subject = Convert.ToString(dr["Title"]);
mail.Body = Convert.ToString(dr["Body"]); //using reply to instead of mail from because of no mail from fields on UI.
string replyTo = Convert.ToString(dr["ReplyTo"]);
if (!string.IsNullOrEmpty(replyTo))
{
mail.Sender = new System.Net.Mail.MailAddress(replyTo);
mail.From = new System.Net.Mail.MailAddress(replyTo);
}
else
{
mail.Sender = new System.Net.Mail.MailAddress(AppSettings.MailDefaultSender);
mail.From = new System.Net.Mail.MailAddress(AppSettings.MailDefaultSender);
} string mailTo = Convert.ToString(dr["MailTo"]);
foreach (string sTemp in mailTo.Split(';'))
{
if (!string.IsNullOrEmpty(sTemp))
{
mail.To.Add(sTemp);
}
} string mailCc = Convert.ToString(dr["MailCc"]);
foreach (string sTemp in mailCc.Split(';'))
{
if (!string.IsNullOrEmpty(sTemp))
{
mail.CC.Add(sTemp);
}
} string mailBcc = Convert.ToString(dr["MailBcc"]);
foreach (string sTemp in mailBcc.Split(';'))
{
if (!string.IsNullOrEmpty(sTemp))
{
mail.Bcc.Add(sTemp);
}
} string attachment = Convert.ToString(dr["Attachments"]);
foreach (string sTemp in attachment.Split(';'))
{
if (!string.IsNullOrEmpty(sTemp))
{
mail.Attachments.Add(new System.Net.Mail.Attachment(sTemp));
}
} mail.IsBodyHtml = true;
mail.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnFailure; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(mailServer);
smtp.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(smtp_SendCompleted);
smtp.SendAsync(mail, taskId);
}
catch (Exception ex)
{
Logging.LogWriter.Write(ex); string sqlText1 = string.Format("UPDATE dbmail_send_task SET [Status]=-1, Remark=N'{0}', MailFrom='ERROR', SendTime=GETDATE(), MailFrom='ERROR' WHERE TaskID={1} ", ex.Message, taskId);
System.Diagnostics.Debug.WriteLine(sqlText1.ToString());
Database.SqlHelper.RunCommand(sqlText1);
}
}
}
catch (Exception ex)
{
Logging.LogWriter.Write(ex);
}
} static void smtp_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
try
{
int taskId = Convert.ToInt32(e.UserState);
if (e.Error != null)
{
string sqlText = string.Format("UPDATE dbmail_send_task SET [Status]=-1, Remark=N'{0}',SendTime=GETDATE(), MailFrom='ERROR' WHERE TaskID={1} ", e.Error.Message, taskId);
System.Diagnostics.Debug.WriteLine(sqlText.ToString());
Database.SqlHelper.RunCommand(sqlText);
}
else
{
string sqlText = string.Format("UPDATE dbmail_send_task SET [Status]=1, SendTime=GETDATE(), Remark=NULL WHERE TaskID={0} ", taskId);
System.Diagnostics.Debug.WriteLine(sqlText.ToString());
Database.SqlHelper.RunCommand(sqlText);
}
}
catch (Exception ex)
{
Logging.LogWriter.Write(ex);
}
} /// <summary>
/// Send out a mail, write log file but no warning returned if any exception
/// </summary>
/// <param name="mailAddress">Include To, CC, BCC mail address</param>
/// <param name="mailContent"></param>
/// <returns></returns>
public static bool SendMessage(MailAddress mailAddress, MailEntity mailContent)
{
string profile = Configuration.AppSettings.MailUserDeliveryProfile;
if (string.IsNullOrEmpty(profile))
{
throw new ArgumentNullException("MailUserDeliveryProfile", "Value of configuration item is required.");
} if (string.IsNullOrEmpty(mailAddress.To))
{
throw new ArgumentNullException("MailAddress.To", "Value of MailTo is required.");
} string sqlText = "sp_HtmlMail_Send @profile=@P0,@mailto=@P1,@mailcc=@P2,@mailbcc=@P3,@replyto=@P4,@title=@P5,@body=@P6,@attachments=@P7,@UserAccountID=@P8,@Remark=@P9"; IDataParameter P0 = new SqlParameter("@P0", SqlDbType.VarChar);
P0.Value = profile;
IDataParameter P1 = new SqlParameter("@P1", SqlDbType.VarChar);
P1.Value = mailAddress.To;
IDataParameter P2 = new SqlParameter("@P2", SqlDbType.VarChar);
P2.Value = mailAddress.Cc;
IDataParameter P3 = new SqlParameter("@P3", SqlDbType.VarChar);
P3.Value = mailAddress.Bcc;
IDataParameter P4 = new SqlParameter("@P4", SqlDbType.VarChar);
P4.Value = mailAddress.ReplyTo;
IDataParameter P5 = new SqlParameter("@P5", SqlDbType.NVarChar);
P5.Value = mailContent.Subject;
IDataParameter P6 = new SqlParameter("@P6", SqlDbType.NVarChar);
P6.Value = CleanHtml(mailContent.Body);
IDataParameter P7 = new SqlParameter("@P7", SqlDbType.NVarChar);
P7.Value = mailContent.Attachments;
IDataParameter P8 = new SqlParameter("@P8", SqlDbType.Int);
if (mailAddress.SendBy > )
{
P8.Value = mailAddress.SendBy;
}
else
{
P8.Value = Security.UserAuthentication.GetCurrentOperator();
}
IDataParameter P9 = new SqlParameter("@P9", SqlDbType.NVarChar);
P9.Value = mailContent.Remark; int result = Database.SqlHelper.RunCommand(sqlText, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9);
if (result > )
{
return true;
}
else
{
return false;
} } /// <summary>
/// Clean up html text
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
private static string CleanHtml(string input)
{
string output = string.Empty;
output = input.Replace(@"\r\n", "<br>");
return output;
} ///// <summary>
///// Encode input string to Unicode
///// </summary>
///// <param name="input"></param>
///// <returns></returns>
//private static string UTF8Str(string input)
//{
// byte[] bs = System.Text.Encoding.Default.GetBytes(input);
// string output = System.Text.Encoding.GetEncoding("UTF-8").GetString(bs);
// return output;
//} //private static string ANSIStr(string input)
//{
// byte[] bs = System.Text.Encoding.Default.GetBytes(input);
// string output = System.Text.Encoding.ASCII.GetString(bs);
// return output;
//} ///// <summary>
///// Convert ununicode string to unicode string.
///// </summary>
///// <param name="str"></param>
///// <returns></returns>
//private static string ConvertToUnicodeString(string str)
//{
// StringBuilder outStr = new StringBuilder();
// if (!string.IsNullOrEmpty(str))
// { // for (int i = 0; i < str.Length; i++)
// {
// if (str[i] > 0xff)
// {
// outStr.AppendFormat("&#{0}", ((int)str[i]).ToString());
// }
// else
// {
// outStr.Append(str[i]);
// }
// }
// }
// return outStr.ToString();
//} } #region Mail Entity /// <summary>
/// Build mail entity, include subject,body, attachments and options.
/// </summary>
public class MailEntity
{
/// <summary>
/// Build a mail entity with template id, you may use -1 if no template id.
/// </summary>
/// <param name="templateId">template id, you may use -1 if no template id.</param>
public MailEntity(int templateId)
{
if (templateId == -)
{
return;
}
else
{
//Load mail template from database according to special template id
string sqlText = string.Format("select * from tb_MailTemplate where ID={0}", templateId);
DataTable dt = Database.SqlHelper.RunQuery(sqlText);
if (dt != null && dt.Rows.Count > )
{
object o = dt.Rows[]["Content"];
if (o != null)
{
_body = o.ToString();
} object title = dt.Rows[]["Title"]; if (title != null)
{
_subject = title.ToString();
}
}
}
} private string _subject = ""; /// <summary>
/// Mail title
/// </summary>
public string Subject
{
get { return _subject; }
set { _subject = value; }
} private string _body = ""; /// <summary>
/// Mail body, html string
/// </summary>
public string Body
{
get { return _body; }
set { _body = value; }
} private string _attachments = ""; /// <summary>
/// Mail attachments, split by "|" if multiple files
/// </summary>
public string Attachments
{
get { return _attachments; }
} private string _attachmentFilePath = ""; public string AttachmentFilePath
{
get { return _attachmentFilePath; }
} private string _remark = ""; /// <summary>
/// Remark
/// </summary>
public string Remark
{
get { return _remark; }
set { _remark = value; }
} /// <summary>
/// Merge field into template
/// </summary>
/// <param name="fieldName"></param>
/// <param name="fieldValue"></param>
public void MergeField(string fieldName, string fieldValue)
{
if (!string.IsNullOrEmpty(_body))
{
_body = _body.Replace(fieldName, fieldValue);
_subject = _subject.Replace(fieldName, fieldValue);
} } /// <summary>
/// Add file as attachment
/// </summary>
/// <param name="fileName"></param>
public void AttachFile(string fileName)
{
if (string.IsNullOrEmpty(_attachments))
{
_attachments = fileName;
}
else
{
_attachments += "|" + fileName;
}
} } #endregion #region Mail Address /// <summary>
/// Build mail address entity, include To, Cc, Bcc
/// </summary>
[Serializable]
public class MailAddress
{
private string _to = ""; /// <summary>
/// Address of mail to
/// </summary>
public string To
{
get { return _to.TrimStart(';'); }
} private string _cc = ""; /// <summary>
/// Address of mail cc
/// </summary>
public string Cc
{
get { return _cc.TrimStart(';'); }
set { _cc = value; }
} private string _bcc = ""; /// <summary>
/// Address of mail bcc
/// </summary>
public string Bcc
{
get { return _bcc.TrimStart(';'); }
} private string _replyTo = ""; /// <summary>
/// Address of mail receiver reply to
/// </summary>
public string ReplyTo
{
get { return _replyTo; }
set { _replyTo = value; }
} private int _sendBy = ; /// <summary>
/// Address of mail send by
/// </summary>
public int SendBy
{
get { return _sendBy; }
set { _sendBy = value; }
} /// <summary>
/// Address of mail sender
/// </summary>
public string From
{
get { return Configuration.AppSettings.MailDeliveryFrom; }
} /// <summary>
/// Add new address to recipients, copy recipients or blind recipients
/// </summary>
/// <param name="address"></param>
/// <param name="addressType"></param>
public void Add(string address, MailAddressType addressType)
{
switch (addressType)
{
case MailAddressType.To:
{
_to = _to + ";" + address;
break;
}
case MailAddressType.Cc:
{
_cc = _cc + ";" + address;
break;
}
case MailAddressType.Bcc:
{
_bcc = _bcc + ";" + address;
break;
}
default: break;
}
} /// <summary>
/// Add new address to recipients, copy recipients or blind recipients
/// </summary>
/// <param name="address"></param>
/// <param name="addressType"></param>
public void Add(string toAddress, string ccAddress, string bccAddress)
{
if (!string.IsNullOrEmpty(toAddress))
{
_to = _to + ";" + toAddress;
} if (!string.IsNullOrEmpty(ccAddress))
{
_cc = _cc + ";" + ccAddress;
} if (!string.IsNullOrEmpty(bccAddress))
{
_bcc = _bcc + ";" + bccAddress;
}
}
} #endregion #region Mail Address Type /// <summary>
/// Mail address type, include To, Cc, Bcc
/// </summary>
public enum MailAddressType
{
To,
Cc,
Bcc
} #endregion }
Email 发送的更多相关文章
- 配置 SQL Server Email 发送以及 Job 的 Notification通知功能
配置 SQL Server Email 发送以及 Job 的 Notification通知功能 在与数据库相关的项目中, 比如像数据库维护, 性能警报, 程序出错警报或通知都会使用到在 SQL Ser ...
- NodeJs之邮件(email)发送
NodeJs之邮件(email)发送 一,介绍与需求 1.1,介绍 1,Nodemailer简介 Nodemailer是一个简单易用的Node.js邮件发送插件 github地址 Nodemailer ...
- python selenium2示例 - email发送
前言 在进行日常的自动化测试实践中,我们总是需要将测试过程中的记录.结果等等等相关信息通过自动的手段发送给相关人员.python的smtplib.email模块为我们提供了很好的email发送等功能的 ...
- Python Email发送,通知业务完成
Email 发送 #!/usr/bin/python # -*- coding: UTF-8 -*- import base64 import smtplib from email.mime.text ...
- Cognos定时Email发送报表数据功能
1:进入 IBM Cognos Configuration-Data Access-Notification 2:设置如下(注意一定要是smtp服务,端口25,我这里是用了腾讯邮箱的smtp服务) 当 ...
- python使用smtplib和email发送腾讯企业邮箱邮件
公司每天要发送日报,最近没事搞了一下如何自动发邮件,用的是腾讯企业邮箱,跟大家分享一下我的研究过程吧. 以前弄的发邮件的是用qq邮箱发的,当时在网上查资料最后达到了能发图片,网页,自定义收件人展示,主 ...
- 【原创】Talend ETL开发——基于joblet的统一的email发送
更新 2019/1/16:增加了允许5个附件发送.smtp等配置的字段. 一.背景 在ETL数据整合过程中,肯定会涉及到email的通知,比如ETL的执行情况汇报,执行耗时汇报,关键数据更新情况等信息 ...
- java email发送(附件中文的处理)
这里使用的是commons-email-1.3.2.jar进行的开发,自认为这是简单的邮件发送. package com.yt.base.common; import java.io.Unsuppor ...
- Android 调用系统Email发送带多附件的邮件
转自:http://www.open-open.com/lib/view/open1347005126912.html 众所周知,在Android中调用其他程序进行相关处理,都是使用的Intent.当 ...
- SpringBoot配置Email发送功能
相信使用过Spring的众多开发者都知道Spring提供了非常好用的 JavaMailSender接口实现邮件发送.在Spring Boot的Starter模块中也为此提供了自动化配置.下面通过实例看 ...
随机推荐
- 分布式锁中的基于redis的setnx的原理以及set和setnx的区别是什么
基于Redis实现分布式锁.虽然网上介绍的Redis分布式锁博客比较多,却有着各种各样的问题,本篇博客将详细介绍如何正确地使用setnx实现Redis分布式锁 这里就不介绍错误的示范了 大家直接看正确 ...
- tail命令 查看文件尾部 输出文件后n行,默认查看文件的后10行
tail命令 查看文件尾部 用于查看日志 默认查看文件的后10行 -n 3 数字 也可以忽略-n 直接加数字 tail 3 查看文件后3行 [root@localhost ~]# tail /e ...
- sqlserver with(nolock)而mysql 不需nolock
nolock 是 SQL Server 特有的功能. 例如:对于一个表 A,更新了一行,还没有commit,这时再select * from A 就会死锁.用select * from A(noloc ...
- Vue.js官方文档学习笔记(三)创建Vue实例
创建Vue实例 每个 Vue 应用都是通过用 Vue 函数创建一个新的 Vue 实例开始的: var vm=new Vue({ //选项 }) Vue的设计受到了mvvm的启发 当创建一个 Vue 实 ...
- ubuntu 个人常用命令
重启命令 : 1.reboot 2.shutdown -r now 立刻重启 3.shutdown -r 10 过10分钟自动重启 4.shutdown -r 20:35 ...
- AtCoder Beginner Contest 072
这应该是我第二次打AtCoder, 题目其实并不难,就是自己经验不足想复杂了,再加上自己很笨,愣是做了97分钟才全做出来(最后三分钟,有点小激动..),看着前面大牛半个小时都搞完了,真心膜拜一下,代码 ...
- 在(U)EFI环境下重装Grub2
本文链接:https://blog.csdn.net/ytingone/article/details/59209526 前段时间重装了系统,导致Grub2的引导消失,所以现在需要进行恢复. 首先需要 ...
- 运维LVS-NAT模式理解
一.LVS-NAT模式的工作原理这个是通过网络地址转换的方法来实现调度的.首先调度器(LB)接收到客户的请求数据包时(请求的目的IP为VIP),根据调度算法决定将请求发送给哪个 后端的真实服务器(RS ...
- Windows 下apache https配置(phpstudy)
1.首先获取证书,https://www.pianyissl.com/ 免费三个月的 或者 自己生成私钥.证书,然后应用到apache中. http://blog.sina.com.cn/s/blo ...
- Delphi 语句