using BookingWeb.DB; using log4net; using MimeKit; using MimeKit.Utils; using MailKit.Net.Smtp; using Quartz; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BookingWeb.Job { public class SendMailJob : IJob { private static readonly int MailSendTryCount = 3; private BookingDB bookingDB = new BookingDB(); private ILog log = LogManager.GetLogger("SendMailJob"); public void Execute(IJobExecutionContext context) { var staCreate = SendMailStatus.Create.ToString(); var staSending = SendMailStatus.Sending.ToString(); var staSuccess = SendMailStatus.Success.ToString(); var staFail = SendMailStatus.Fail.ToString(); var sendMail = bookingDB.SendMails.Where(m => m.STATUS == staCreate).OrderBy(m => m.CREATE_TIME).FirstOrDefault(); if (sendMail != null) { //置发送状态 log.Debug($"准备发送邮件:{sendMail.TITLE}"); sendMail.STATUS = staSending; sendMail.SEND_TIME = DateTime.Now; sendMail.TRY_COUNT += 1; bookingDB.SaveChanges(); //获取配置并发送 var clientConfig = bookingDB.Clients.FirstOrDefault(c => c.GID == sendMail.CLIENT_ID); if (clientConfig == null) { log.Error($"邮件<{sendMail.TITLE}>发送失败:找不到ID为{sendMail.CLIENT_ID}的CLIENT"); return; } else if (string.IsNullOrEmpty(clientConfig.SMTP_SERVER) || string.IsNullOrEmpty(clientConfig.MAIL_ACCOUNT) || string.IsNullOrEmpty(clientConfig.MAIL_PASSWORD)) { log.Error($"邮件<{sendMail.TITLE}>发送失败:ID为{sendMail.CLIENT_ID}的CLIENT未正确配置邮件发送服务器"); return; } else { var message = new MimeMessage(); message.Subject = sendMail.TITLE; message.To.Add(new MailboxAddress(sendMail.SEND_TO)); message.MessageId = MimeUtils.GenerateMessageId(); message.Date = DateTimeOffset.Now; message.From.Add(new MailboxAddress(clientConfig.MAIL_ACCOUNT)); if (!string.IsNullOrEmpty(sendMail.CC_TO)) { message.Cc.Add(new MailboxAddress(sendMail.CC_TO)); } if (sendMail.BODY_TYPE == SendMailBodyType.Text.ToString()) { var plain = new TextPart("plain") { Text = sendMail.BODY }; message.Body = plain; } try { using (var client = new SmtpClient()) { client.Connect(clientConfig.SMTP_SERVER, clientConfig.SMTP_PORT, clientConfig.SMTP_SSL); client.Authenticate(clientConfig.MAIL_ACCOUNT, clientConfig.MAIL_PASSWORD); client.Send(message); log.Debug($"已发送邮件:{message.Subject}"); client.Disconnect(true); } sendMail.STATUS = staSuccess; bookingDB.SaveChanges(); } catch (Exception ex) { if (sendMail.TRY_COUNT < MailSendTryCount) //会继续尝试发送 { sendMail.STATUS = staCreate; bookingDB.SaveChanges(); } else { sendMail.STATUS = staFail; bookingDB.SaveChanges(); } log.Error($"发送邮件<{message.Subject}>时出错:"); log.Error($"{ex.Message}"); log.Error($"{ex.StackTrace}"); } } } } } }