C#定时发送邮件功能
背景
自动运维监控客户端在自动关闭时,需要给实施同学发送提醒邮件。支持163邮箱、qq邮箱、火狐邮箱等各种通用邮箱。
定时器+发送邮件
代码
邮件功能模块
using ITSLog.LogManage;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;namespace SystemMonitor.Util
{public static class MailModel{private static KSLog log = LogService.GetKSlog(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);/// <summary>/// 发送邮件/// </summary>/// <param name="mailEntity"></param>public static void SendMonitorEmail(MailEntity mailEntity){//MailMessage mail = new MailMessage(mailEntity.SendMailAdress, mailEntity.ReciveAdress);MailMessage mail = new MailMessage();mail.From = new MailAddress(mailEntity.SendMailAdress);foreach (var toItem in mailEntity.ReciveAdress){mail.To.Add(new MailAddress(toItem));}SmtpClient client = new SmtpClient();// 设置SMTP服务器和其他参数 //client.Port = 465; // SMTP端口(通常用于TLS) client.DeliveryMethod = SmtpDeliveryMethod.Network;//使用自己的验证邮件设置为falseclient.UseDefaultCredentials = false;client.EnableSsl = true;// 你的SMTP服务器地址 string[] addressor = mailEntity.SendMailAdress.Split(new Char[] { '@', '.' });switch (addressor[1]){case "163":client.Host = "smtp.163.com";break;case "126":client.Host = "smtp.126.com";break;case "qq":client.Host = "smtp.qq.com";break;case "gmail":client.Host = "smtp.gmail.com";break;case "hotmail":client.Host = "smtp.live.com";//outlook邮箱//client.Port = 587;break;case "foxmail":client.Host = "smtp.foxmail.com";break;case "sina":client.Host = "smtp.sina.com.cn";break;default:client.Host = "smtp.exmail.qq.com";//qq企业邮箱break;}//client.Host = mailEntity.StmpHost;// 设置你的邮箱凭据(如果需要) NetworkCredential credentials = new NetworkCredential(mailEntity.UseCode, mailEntity.PassWord);client.Credentials = credentials;// 设置邮件内容 mail.Subject = mailEntity.MailSubject;mail.Body = mailEntity.MailBody;mail.SubjectEncoding = System.Text.Encoding.UTF8;mail.BodyEncoding = System.Text.Encoding.UTF8;mail.Priority = System.Net.Mail.MailPriority.Normal;mail.IsBodyHtml = true;mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;if (mailEntity.accessoryPath != null){foreach (string path in mailEntity.accessoryPath){//将附件添加到邮件mail.Attachments.Add(new Attachment(path));//获取或设置此电子邮件的发送通知。mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;}}// 发送邮件 try{client.Send(mail);log.Debug(DateTime.Now.ToString() + "邮件发送成功");}catch (Exception ex){log.Debug("初始化停止启动日期失败 :" + ex.ToString());}finally{client.Dispose();}}}/// <summary>/// 邮件实体类/// </summary>public class MailEntity{/// <summary>/// 发送地址/// </summary>public string SendMailAdress;/// <summary>/// 接收地址/// </summary>public List<string> ReciveAdress;/// <summary>/// 用户/// </summary>public string UseCode;/// <summary>/// 密码/// </summary>public string PassWord;/// <summary>/// 标题/// </summary>public string MailSubject;/// <summary>/// 邮件主体/// </summary>public string MailBody;/// <summary>/// 抄送地址/// </summary>public List<string> accessoryPath { get; set; }}
}
调用模块
#region 邮件发送相关/// <summary>/// 邮件触发器/// </summary>private System.Windows.Forms.Timer dailyMailTimer;/// <summary>/// /// </summary>private DateTime nextRunTime = DateTime.MinValue; // 初始化为一个无效时间 private void InitializeTimer(){dailyMailTimer = new System.Windows.Forms.Timer();dailyMailTimer.Interval = 1000; // 1秒,用于检查时间 dailyMailTimer.Tick += DailyTimer_Tick;dailyMailTimer.Start(); // 启动Timer }private void SetNextRunTime(){// 设置下一次运行时间为今天的15:50,如果已经过了这个时间,则设置为明天的15:50 DateTime now = DateTime.Now;closeTime = Convert.ToDateTime(ConvertDate(InitDate)).Add(TimeSpan.Parse(Config.AutoCloseTime));DateTime sendMailTime = closeTime.AddMinutes(10);if (sendMailTime < now){sendMailTime = sendMailTime.AddDays(1); // 设置为明天的同一时间 }nextRunTime = sendMailTime;}private void DailyTimer_Tick(object sender, EventArgs e){if (DateTime.Now >= nextRunTime){dailyMailTimer.Stop(); // 停止Timer,防止在SendEmail期间再次触发 SendEmail(); // 执行任务 SetNextRunTime(); // 重置下一次运行时间 dailyMailTimer.Start(); // 重新启动Timer }}/// <summary>/// 校验条件满足送发邮件/// </summary>public void SendEmail(){if (Config.SendMailAddress == "" || Config.SendMailAddress == null) return;if (Config.ReciveMailAddress == "" || Config.ReciveMailAddress == null) return;if (Config.Mailsecret == "" || Config.Mailsecret == null) return;if (true)//校验条件{MailEntity mailEntity = new MailEntity{SendMailAdress = Config.SendMailAddress,UseCode = Config.SendMailAddress,ReciveAdress = new System.Collections.Generic.List<string>() { Config.ReciveMailAddress },PassWord = Config.Mailsecret,MailSubject = "邮件名称",MailBody = "邮件主体"};MailModel.SendMonitorEmail(mailEntity);}}#endregion
邮箱设置
生活不易,猫猫叹气。Q-Q