其他分享
首页 > 其他分享> > MailKit 读取邮件附件

MailKit 读取邮件附件

作者:互联网

  static DbContext db = new DbContext();
        /// <summary>
        /// 下载邮件附件
        /// </summary>
        [HttpGet]
        public void GetEmailFile()
        {
            Console.WriteLine("Hello, World!");
            string serve = "";
            string Account = "";
            string pwd = "";

            //查读取过的邮件id
            List<string> EmailCodeList = (from i in db.Emaillog.GetList() select i.EmailCode).ToList();
            using (var client = new ImapClient())
            {
                #region 连接邮件服务器获取所有邮件
//我们用的端口号是143,SecureScokeroptions是一个枚举类型,邮箱加密方式 client.Connect(serve, 143, SecureSocketOptions.None); client.Authenticate(Account, pwd); // The Inbox folder is always available on all IMAP servers... var inbox = client.Inbox; //以读写的方式打开收件箱方便设置邮件状态 inbox.Open(FolderAccess.ReadOnly); //获取所有邮件编号 var uids = inbox.Search(SearchQuery.All); #endregion //获取邮件信息 for (int i = 0; i < uids.Count; i++) { //如果读取到的邮件编号没有被存储过就会读取邮件附件 if (!EmailCodeList.Contains(uids[i].ToString())) { List<string> files = new List<string>(); //只获取当前的循环的邮件编号便于可能操作数据库,分辨邮件 List<UniqueId> uniqueIds = new List<UniqueId> { uids[i] };
//通过邮件编号设置获取邮件内容 var message = inbox.GetMessage(uids[i]); string msgId = message.MessageId; Console.WriteLine("Subject: {0}", message.Subject); Console.WriteLine("Headers: {0}", message.Headers); //获取附件 var listmsg = client.Inbox.Fetch(uniqueIds, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure); Emaillog maillog = new maillog() { CreateTime = DateTime.Now, EmailCode = uids[i].ToString(), ReceivingTime = message.Date.ToString(), Subject = message.Subject, Status = true }; foreach (var item in listmsg) { // 确定一个目录来保存内容 var directory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "MailBody"); Directory.CreateDirectory(directory); // 现在遍历所有附件并将其保存到磁盘 foreach (var attachment in item.Attachments) { // 像我们对内容所做的那样下载附件 var entity = client.Inbox.GetBodyPart(item.UniqueId, attachment); // 附件可以是message / rfc822部件或常规MIME部件 var messagePart = entity as MessagePart; if (messagePart != null) { var rfc822 = messagePart; var path = Path.Combine(directory, attachment.PartSpecifier + ".eml"); rfc822.Message.WriteTo(path); } else { var part = (MimePart)entity; // 注意:这可能是空的,但大多数会指定一个文件名 var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"; var path = Path.Combine(directory, fileName); // decode and save the content to a file using (var stream = System.IO.File.Create(path)) part.Content.DecodeTo(stream); //读到文件之后记录存放文件路径 files.Add(path); maillog.AttachmentPath = maillog.AttachmentPath + path; } } } try { db.Db.BeginTran(); foreach (var item in files) { ImportExcel(item); } var status = db.Emaillog.Insert(Emaillog); db.Db.CommitTran(); } catch (Exception ex) { db.Db.RollbackTran(); //回滚之后记录错误日志 maillog.Status = false; maillog.Msg = ex.Message; var status = db.Emaillog.Insert(maillog); } //你可以以读写的方式打开最后设置邮件状态为已读 //MessageFlags messageFlags = MessageFlags.Seen; //bool silent = false; //inbox.SetFlags(uids[i], messageFlags, silent); } } client.Disconnect(true); } Console.ReadKey(); } [NonAction] public static void ImportExcel(string path) { List<trackingnumber> trackingnumbers = new List<trackingnumber>(); using (var package = new ExcelPackage(new FileInfo(path))) { var sheet = package.Workbook.Worksheets[1]; var colCount = sheet.Dimension.End.Column; var rowCount = sheet.Dimension.End.Row; for (int c = sheet.Dimension.Start.Column; c <= rowCount; c++) { if (c != 1) { var value = sheet.GetValue<string>(c, 1); var value2 = sheet.GetValue<string>(c, 2); trackingnumbers.Add(new trackingnumber { CreateTime = DateTime.Now, OrderNumber = value, TrackingNumber = value2, Status = false }); } } } var sta = db.trackingnumber.InsertRange(trackingnumbers); }

  

标签:邮件附件,MailKit,读取,db,path,var,new,邮件,uids
来源: https://www.cnblogs.com/myleave/p/15438150.html