C#获取邮箱邮件信息+附件下载
需求:客户通过邮件发送报表,我方自行下载上传更新到系统
目标:自动下载到服务器,然后再自动读取到系统上。
邮箱设置:
这里可以设置自动移动到此文件夹的规则(我这里设置了针对固定客户的发送邮箱、表头内容包括哪些字的、以及带有附件之类其它的条件)
引用包【MailKit】:
using MailKit; using MailKit.Net.Imap; using MailKit.Search; using MimeKit;
代码:
/// <summary> /// IMAP 读取邮箱信息 MimeKit包下 /// </summary> public static void IMAP() { try { //注册字符集,缺失字符集,一些中文编码数据为乱码 --千万别删,不然就是乱码了 Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // 设置IMAP服务器地址、端口、用户名和密码 string imapServer = "smtp.com"; int port = 993;//这里是993,不要考虑什么110、25的 string username = ""; //用户名 string password = ""; //密码 // 创建IMAP客户端 using (var client = new ImapClient()) { //client.Connect(imapServer, port, true); client.Connect(imapServer); client.Authenticate(username, password); // 打开发件箱 不可随哟更改邮箱文件夹名称和移动邮件 //var folder = client.GetFolder("已发送邮件"); var folder = client.GetFolder("StockReleationFiles");//这里是你邮箱的文件夹(需要自己在邮箱设置) folder.Open(FolderAccess.ReadOnly); // 获取收件箱中的邮件数量 Console.WriteLine("收件箱中共有 {0} 封邮件", folder.Count); //获取昨天到今天的邮件 一般两天足已 var uidss = folder.Search(SearchQuery.DeliveredAfter(DateTime.Parse(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd")))); string savePath = @"D:\Syn\Email\"; if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath); //获取完整邮件 foreach (var item in uidss) { MimeMessage message = folder.GetMessage(new UniqueId(item.Id)); Console.WriteLine("邮件主题:{0}", message.Subject); //获取邮件附件 var files = folder.GetMessage(new UniqueId(item.Id)); var items = files.Attachments; foreach (var attachment in items) { if (attachment is MessagePart) { var fileName = attachment.ContentDisposition?.FileName; var rfc = (MessagePart)attachment; if (string.IsNullOrEmpty(fileName)) fileName = "attached-message.eml"; Console.WriteLine("邮件附件文件:{0}", fileName); //下载 using (var stream = File.Create(savePath + fileName)) { rfc.Message.WriteTo(stream); } } else { var part = (MimePart)attachment; var fileName = part.FileName; Console.WriteLine("邮件附件文件:{0}", fileName); //下载 using (var stream = File.Create(savePath + fileName)) { part.Content.DecodeTo(stream); } } } }
//必须得关,坑已经踩过了 client.Disconnect(true); client.Dispose(); } } catch (Exception ex) { Console.WriteLine("读取收件箱失败:" + ex.Message); } }
补充:
//获取未读的邮件 var uidss = folder.Search(SearchQuery.NotSeen);
//标记已读(这里记得将前面的模式改成ReadWrite =》 folder.Open(FolderAccess.ReadWrite); ) folder.SetFlags(new UniqueId(item.Id), MessageFlags.Seen, true);
//内容按照换行分隔 string[] lines = content.Split(new string[] { "\r\n" }, StringSplitOptions.None);
参考:https://blog.csdn.net/qq_44384774/article/details/139686615
https://blog.csdn.net/weixin_45792450/article/details/104322252?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-104322252-blog-2047410.235^v43^pc_blog_bottom_relevance_base7&spm=1001.2101.3001.4242.1&utm_relevant_index=1
https://blog.csdn.net/qq_43170460/article/details/117034942