using log4net; using Quartz; using System; using System.Data; using System.IO; using System.Linq; using System.Text; using MailKit; using MailKit.Net.Imap; using MailKit.Search; using MimeKit; using System.Data.Entity; using System.Data.SqlClient; namespace JobSendAgentMail { public class MailDataContext : DbContext { public MailDataContext(string nameOrConnectionString) : base(nameOrConnectionString) { } public DbSet ReceiveRecords { get; set; } public DbSet MailSend { get; set; } public DbSet OpMailLogs { get; set; } } public class D7OPSEAEMAIL { public string BSNO { get; set; } public string AGENTMAIL { get; set; } public string OPEMAIL { get; set; } public string MBLNO { get; set; } public string HBLNO { get; set; } public string INVNO { get; set; } } public class JobReceiveMail : IJob { private ILog log = LogManager.GetLogger(typeof(JobReceiveMail)); public void Execute(IJobExecutionContext context) { string connStr = context.JobDetail.JobDataMap.GetString("ConnectString"); string querySql = context.JobDetail.JobDataMap.GetString("QuerySql"); string hblquerySql = context.JobDetail.JobDataMap.GetString("HblQuerySql"); string DocType = context.JobDetail.JobDataMap.GetString("DocType"); string D7FilePath = context.JobDetail.JobDataMap.GetString("D7FilePath"); string MAILSENDACCOUNT = context.JobDetail.JobDataMap.GetString("MAILSENDACCOUNT"); string MAILSENDPASSWORD = context.JobDetail.JobDataMap.GetString("MAILSENDPASSWORD"); string MAILSENDSERVICE = context.JobDetail.JobDataMap.GetString("MAILSENDSERVICE"); string MAILSENDPORT = context.JobDetail.JobDataMap.GetString("MAILSENDPORT"); string MAILISSSL = context.JobDetail.JobDataMap.GetString("MAILISSSL"); string MAILTEMPLATE = context.JobDetail.JobDataMap.GetString("MAILTEMPLATE"); string MAILTITLE = context.JobDetail.JobDataMap.GetString("MAILTITLE"); string basePath = AppDomain.CurrentDomain.BaseDirectory; string savePath = Path.Combine(basePath, $"{DateTime.Now.ToString("yyyyMMdd")}\\{MAILSENDACCOUNT}"); log.Debug($"开始接收邮件"); using (SqlConnection dbcon = new SqlConnection(connStr)) { dbcon.Open(); using (var imapClient = new ImapClient()) { imapClient.ServerCertificateValidationCallback = (s, c, h, e) => true; imapClient.Connect(MAILSENDSERVICE, Convert.ToInt16(MAILSENDPORT), Convert.ToBoolean(MAILISSSL)); imapClient.Authenticate(MAILSENDACCOUNT, MAILSENDPASSWORD); log.Debug($"已连接邮件"); var inbox = imapClient.Inbox; inbox.Open(FolderAccess.ReadOnly); MailDataContext mailData = new MailDataContext(connStr); var uids = inbox.Search(SearchQuery.DeliveredAfter(DateTime.Now).And(SearchQuery.DeliveredBefore(DateTime.Now.AddDays(1)))); //MailDataContext dataContext = new MailDataContext(connStr); for (int i = 0; i < uids.Count; i++) { var uid = uids[i]; var c = mailData.ReceiveRecords.Count(r => r.MailAccount == MAILSENDACCOUNT && r.MailId == uid.Id); if (c > 0) { continue; //忽略 } try { var recInfo = new MailReceiveRecordInfo(); recInfo.MailAccount = MAILSENDACCOUNT; recInfo.MailId = uid.Id; recInfo.MailDate = DateTime.Now; string emlSavePath = Path.Combine(savePath, $"{uid}.eml"); var message = inbox.GetMessage(uid); //message.WriteTo(emlSavePath); recInfo.Subject = message.Subject; recInfo.Sender = message.From[0].ToString(); recInfo.RecTime = message.Date.ToLocalTime().DateTime; if (recInfo.RecTime < DateTime.Parse("1970-01-01")) { recInfo.RecTime = DateTime.Now; } #region body乱码处理 string body = string.Empty; //if (message.TextBody != null) //{ // body = message.TextBody; //} //else if (message.HtmlBody != null) //{ // body = message.HtmlBody; //} recInfo.Body = message.HtmlBody; #endregion string strAttach = string.Empty; foreach (var att in message.Attachments) { MimePart attPart = att as MimePart; if (attPart != null) { strAttach += attPart.FileName + ";"; } } recInfo.Attachments = strAttach; recInfo.FilePath = emlSavePath; mailData.ReceiveRecords.Add(recInfo); mailData.SaveChanges(); //立即保存 log.Debug($"已保存邮件"); if (recInfo.Subject.IndexOf("SZNG HBL") == 0) { log.Debug($"分析邮件"); var mailsubject = recInfo.Subject; var subjectlist = mailsubject.Split(':'); if (subjectlist.Length >=3) { var STATUS = ""; var HBLNO = subjectlist[0].Replace("SZNG HBL","").Trim(); log.Debug($"分析邮件:"+HBLNO+" "+STATUS); var statuslist = subjectlist[2].Split(' '); if (statuslist.Length >= 0) STATUS = statuslist[2].Trim(); if (!string.IsNullOrEmpty(HBLNO) && !string.IsNullOrEmpty(STATUS)) { var tastStr = $" update op_seae_edi set MANIFESTSTATUS=MANIFESTSTATUS+' '+'{STATUS}' where HBLNO='{HBLNO}' AND MANIFESTSTATUS not like '%{STATUS}%' "; SqlCommand cmdtast = new SqlCommand(tastStr, dbcon); cmdtast.ExecuteNonQuery(); log.Debug($"更新舱单状态:" + HBLNO + " " + STATUS); var AGENTMAIL = AGENTEMAIL(HBLNO, querySql,dbcon); if (!string.IsNullOrEmpty(AGENTMAIL.AGENTMAIL)) { log.Debug($"生成转发:" + HBLNO + " " + STATUS); MAILTITLE = MAILTITLE.Replace("$MBLNO$", AGENTMAIL.MBLNO); MAILTITLE = MAILTITLE.Replace("$INVNO$",AGENTMAIL.INVNO); MAILTITLE = MAILTITLE.Replace("$MAILTITLE$", recInfo.Subject); var sendmail = new MailSend(); sendmail.GID = Guid.NewGuid().ToString(); sendmail.Title = MAILTITLE; sendmail.Body = recInfo.Body; sendmail.SendTo = AGENTMAIL.AGENTMAIL; sendmail.CCTo= AGENTMAIL.OPEMAIL; sendmail.RelativeId = AGENTMAIL.BSNO; sendmail.SendStatus = "Create"; sendmail.CreateTime = DateTime.Now; sendmail.TryCount = 0; mailData.MailSend.Add(sendmail); mailData.SaveChanges(); log.Debug($"保存转发:" + HBLNO + " " + STATUS); } } } } mailData.Dispose(); mailData = null; } catch (Exception ex) { log.Error($"收取邮件时,发生严重错误:{uid}"); log.Error(ex.Message); log.Error(ex.StackTrace); } } if (inbox.IsOpen) { inbox.Close(); imapClient.Disconnect(true); } } dbcon.Close(); } } static public D7OPSEAEMAIL AGENTEMAIL(string HBLNO,string QuerySql,SqlConnection dbcon) { var result = new D7OPSEAEMAIL(); QuerySql = QuerySql.Replace("@HBLNO", HBLNO); SqlDataAdapter adapter = new SqlDataAdapter(QuerySql, dbcon); DataTable table = new DataTable(); adapter.Fill(table); if (table.Columns.Contains("BSNO") && table.Columns.Contains("AGENTEMAIL")) { if (table.Rows.Count > 0) { foreach (DataRow row in table.Rows) { result.AGENTMAIL = row["AGENTEMAIL"].ToString(); result.OPEMAIL = row["OPEMAIL"].ToString(); result.BSNO = row["BSNO"].ToString(); result.INVNO = row["INVNO"].ToString(); result.MBLNO = row["MBLNO"].ToString(); } } } return result; } } }