菜鸟D在工作时,用户提到要给系统添加一个定时发送邮件的功能,这个菜鸟D没有写过,只是知道基本原理是怎么回事。根据我的想法:新开一个线程,线程中添加一个计时器,由计时器来完成定时的任务。至于发送邮件,写个方法就OK了,毕竟网上封装好的发送邮件功能都烂大街了。但是在实际工作的时候却发生一些意外,比如线程什么时候开启?随时用随时开启还是一启动就开启,毋庸置疑是后者嚒。有了思路一切都好办了,在网上搜索一部分资料整理如下:
自动发送邮件,通常使用的几种方法:
1.使用winform做UI时,可以在程序的load事件中,或者其他控件驱动事件中执行邮件发送任务。定时功能可以通过Windows的计划任务,设置指定时间执行winform程序,执行完成之后自动关闭即可。
2.使用sqlserver数据库发送邮件,使用sqlserver实现发送邮件的存储过程,指定定时执行。(此方法未尝试,具体过程下文详细转述)
3.使用web做UI时,可以在Global.asax全局文件里做一些编程。事件Application_Start。自动定时执行可以交给计时器timer来执行。
接下来介绍一些需要注意的地方:
1.可以封装一个邮件发送的操作类,便于移植及日后的使用。
2.在全局文件里做定时执行的任务,个人建议使用线程和计时器,保证主线程的正常运行。(System.Timers.Timer; System.Threading.Timer;System.Web.UI.Timer 共有三种计时器,由于自动发送邮件在服务器端执行,此例中个人建议使用第一种,其他情况具体分析,可参见)
下面详述方法2:
通过Sqlserver发送邮件:
一.启用Database Mail XPs功能。查看Database Mail XPs功能是否打开,从返回结果来看,value为0说明没有打开,注意SQL Mail XPs是SQL Server早期版本提供的发送邮件功能,而现在用的是Database Mail XPs来实现发送邮件。
select name, value, description, is_dynamic, is_advanced from sys.configurations where name like ‘%mail%‘ /*name value description is_dynamic is_advancedSQL Mail XPs 0 Enable or disable SQL Mail XPs 1 1Database Mail XPs 0 Enable or disable Database Mail XPs 1 1*/ 启动Database Mail XPs功能: sp_configure ‘show advanced options‘,1 go reconfigure go sp_configure ‘Database Mail XPs‘,1 go reconfigure go
二、配置数据库邮件
1、点开管理目录,右键“数据库邮件”,选择“配置数据库邮件”选项;
2、弹出“数据库邮件配置向导”,单击下一步:
3、选择“通过执行以下任务来安装数据库邮件”选项,单击下一步:
4、输入“配置文件名”,这里我输入的是:db_mail,然后单击右侧的“添加”按钮:
5、输入账户名、说明,按照你的实际情况,输入:电子邮件地址、服务器名称,用户名和密码,必须要输入正确,否则就不能正确发送邮件。
6、填写完成后,单击下一步:
7、在“公共”选项打上勾,单击下一步:
8、可以修改“配置系统参数”,比如账户重试次数,禁止的附件文件扩展名,单击下一步:
9、单击完成按钮,显示配置成功。
三、发送邮件
DECLARE @email_conetent VARCHAR(8000); --存放邮件正文--计算有多少条记录 SELECT @email_conetent = ‘你的数据库,共有:‘+ cast(COUNT(*) as varchar) + ‘个表!‘ FROM sys.tables; --发送邮件 EXEC msdb.dbo.sp_send_dbmail @profile_name = ‘db_mail‘, --配置文件名称 @recipients = ‘[email protected]‘, --收件email地址 @subject = ‘你好‘, --邮件主题 @body = @email_conetent --邮件正文内容
四、查看数据库邮件日志。右键“数据库邮件”,选择“查看数据库邮件日志”:
下面简述方法3:
protected void Application_Start(object sender, EventArgs e) //Global.asax { Timer t = new Timer(60000);//设计时间间隔,如果一个小时执行一次就改为3600000 ,这里一分钟调用一次 t.Elapsed += new ElapsedEventHandler(t_Elapsed); t.AutoReset = true; //默认为true,可省略 t.Enabled = true; } private void t_Elapsed(object sender, ElapsedEventArgs e) { //根据具体需要,添加具体功能 }
附:个人整理的邮件发送类
public class EmailHelper { #region 字段属性 /// <summary> /// 发件箱服务器 /// </summary> public string SendServer { get; set; } /// <summary> /// 收件人邮箱,多人以“;”分割 /// </summary> public string ToMail { get; set; } /// <summary> /// 发件人邮箱 /// </summary> public string FromMail { get; set; } /// <summary> /// 发件人密码 /// </summary> public string Pwd { get; set; } /// <summary> /// 邮件标题 /// </summary> public string Subject { get; set; } /// <summary> /// 邮件内容 /// </summary> public string EmailBody { get; set; } /// <summary> /// 发送邮件的端口,默认是25 /// </summary> private string prot = "25"; /// <summary> /// 是否使用socket加密传输 /// </summary> public bool SslEnable { get; set; } /// <summary> /// 是否对发件人邮箱进行密码验证 /// </summary> public bool PwdCheckEnable { get; set; } /// <summary> /// 发送邮件的端口,默认是25 /// </summary> public string Prot { get { return prot; } set { prot = value; } } /// <summary> /// 邮件 /// </summary> private MailMessage mailMessage; /// <summary> /// 发件服务器 /// </summary> private SmtpClient smtpClient; private string username; #endregion #region 构造方法 public EmailHelper() : this(null, null, null) { } public EmailHelper(string tomail, string frommail, string pwd) : this(tomail, frommail, pwd, null, null) { } public EmailHelper(string tomail, string frommail, string pwd, string subject = null, string emailbody = null) : this(tomail, frommail, pwd, subject, emailbody, true, true) { } /// <param name="tomail">收件箱地址,可以使用;隔开多个收件人地址</param> /// <param name="frommail">发件箱地址</param> /// <param name="subject">邮件主题</param> /// <param name="emailbody">邮件内容</param> /// <param name="pwd">发件箱密码</param> /// <param name="sslEnable">是否ssl加密传输</param> /// <param name="pwdcheckEnable">是否验证发件人邮箱密码</param> public EmailHelper(string tomail, string frommail, string pwd, string subject, string emailbody, bool sslEnable = true, bool pwdcheckEnable = true) : this(SmtpClientComm.GetSmtp(frommail), tomail, frommail, pwd, subject, emailbody, sslEnable, pwdcheckEnable) { } /// <summary> /// 不常用的邮件服务器 /// </summary> /// <param name="stmpclient">不常用的邮件服务器</param> /// <param name="tomail">收件箱地址,可以使用;隔开多个收件人地址</param> /// <param name="frommail">发件箱地址</param> /// <param name="subject">邮件主题</param> /// <param name="emailbody">邮件内容</param> /// <param name="pwd">发件箱密码</param> /// <param name="sslEnable">是否ssl加密传输</param> /// <param name="pwdcheckEnable">是否验证发件人邮箱密码</param> public EmailHelper(string stmpclient, string tomail, string frommail, string pwd, string subject, string emailbody, bool sslEnable = true, bool pwdcheckEnable = true) { ToMail = tomail; FromMail = frommail; Subject = subject; EmailBody = emailbody; Pwd = pwd; SslEnable = sslEnable; PwdCheckEnable = pwdcheckEnable; username = frommail.Substring(0, frommail.IndexOf("@")); SendServer = stmpclient; } #endregion #region 初始化 /// <summary> /// 初始化邮件服务器 /// </summary> private void InitSmtpClient() { smtpClient = new SmtpClient(); smtpClient.Host = SendServer; smtpClient.Port = Convert.ToInt32(Prot); smtpClient.UseDefaultCredentials = true; smtpClient.EnableSsl = SslEnable; smtpClient.Credentials = new NetworkCredential(username, Pwd); } /// <summary> /// 初始化邮件信息 /// </summary> private void InitMailMessage() { mailMessage = new MailMessage(); mailMessage.To.Add(ToMail); if (ToMail.Contains(";")) { mailMessage.To.Clear(); foreach (var item in ToMail.Split(new[] { ‘;‘ }, StringSplitOptions.RemoveEmptyEntries)) { mailMessage.To.Add(item); } } mailMessage.From = new MailAddress(FromMail, username); mailMessage.Subject = Subject; mailMessage.SubjectEncoding = Encoding.UTF8; mailMessage.Body = EmailBody; mailMessage.IsBodyHtml = true; mailMessage.Priority = MailPriority.Normal; } #endregion /// <summary> /// 发送邮件 /// </summary> public void Send() { InitMailMessage(); InitSmtpClient(); try { if (mailMessage != null) { smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.Send(mailMessage); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } /// <summary> /// 添加附件,多个附件使用“;”隔开 /// </summary> public void AddAttachments(string paths) { try { string[] path = paths.Split(new[] { ‘;‘ }, StringSplitOptions.RemoveEmptyEntries); Attachment data; ContentDisposition disposition; for (int i = 0; i < path.Length; i++) { data = new Attachment(path[i], MediaTypeNames.Application.Octet); disposition = data.ContentDisposition; disposition.CreationDate = File.GetCreationTime(path[i]); disposition.ModificationDate = File.GetLastWriteTime(path[i]); disposition.ReadDate = File.GetLastAccessTime(path[i]); mailMessage.Attachments.Add(data); } } catch (Exception ex) { throw; } } } /// <summary> /// 常用的stmp服务器 /// </summary> public class SmtpClientComm { public const string Smtp163 = "smtp.163.com"; public const string Smtp126 = "smtp.126.com"; public const string SmtpQQ = "smtp.qq.com"; public const string Smtp188 = "smtp.188.com"; public const string SmtpYeah = "smtp.yeah.net"; public const string SmtpSina = "smtp.sina.com"; public const string SmtpSohu = "smtp.sohu.com"; public const string SmtpTom = "smtp.tom.com"; public const string SmtpGmail = "smtp.gmail.com"; public const string Smtp139 = "smtp.139.com"; /// <summary> /// 根据发件箱获取邮件服务器 /// </summary> public static string GetSmtp(string FromMail) { string stmp = string.Empty; if (string.IsNullOrEmpty(FromMail)) { return ""; } switch (FromMail.Substring(FromMail.IndexOf("@", StringComparison.Ordinal) + 1).ToLower()) { case "126.com": stmp = Smtp126; break; case "163.com": stmp = Smtp163; break; case "qq.com": stmp = SmtpQQ; break; case "188.com": stmp = Smtp188; break; case "yeah.net": stmp = SmtpYeah; break; case "sina.com": stmp = SmtpSina; break; case "sohu.com": stmp = SmtpSohu; break; case "tom.com": stmp = SmtpTom; break; case "gmail.com": stmp = SmtpGmail; break; case "139.com": stmp = Smtp139; break; } if (string.IsNullOrEmpty(stmp)) { throw new Exception("未找到对应的邮件服务器"); } return stmp; } }
//邮件测试 EmailHelper em = new EmailHelper("smtp.163.com", "tomail", "frommail", "pwd", "测试", "这是一封测试邮件:http://www.baidu.com", true, false); em.Send();
-----------------------------------------------------------------------------------------
菜鸟D希望这些文字对您有所帮助。