开发工具 vs2022,新建-控制台应用。项目完整代码下载:https://download.csdn.net/download/mangge/89955534?spm=1001.2014.3001.5503
要安装MailKit库
using MailKit;
using MailKit.Net.Imap;
using MimeKit;
using System.Text;
namespace MailKit_mail
{internal class Program{static void Main(string[] args){//需要使用 MailKit 库 Install-Package MailKit //注册字符集,缺失字符集,一些中文编码数据为乱码 --千万别删,不然就是乱码了 //参考:https://blog.csdn.net/qq_44384774/article/details/139686615Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);// IMAP服务器的信息string host = "imap.139.com";int port = 993;bool useSsl = true;string username = "138********@139.com"; //账号string password = "***************"; //密码using (var imapClient = new ImapClient()){// 连接到IMAP服务器imapClient.Connect(host, port, useSsl);// 登录到邮箱imapClient.Authenticate(username, password);// 选择INBOX文件夹imapClient.Inbox.Open(FolderAccess.ReadOnly);// 获取INBOX中所有的邮件var count = imapClient.Inbox.Count;Console.WriteLine("邮件数量:{0}", count);// 获取邮件for (int i = 0; i < 20; i++){MimeMessage message = imapClient.Inbox.GetMessage(i);//Console.WriteLine("{0}主题:{1}", i.ToString(), message.Subject);Console.WriteLine($"\r\n标题:{message.Subject} \r\n内容:{message.TextBody}\r\n");// 处理邮件附件foreach (var attachment in message.Attachments){if (attachment.IsAttachment)if (attachment is MimePart){var part = (MimePart)attachment;var fileName = part.FileName;//var filePath = "D:\\tmp\\" + Guid.NewGuid().ToString() + fileName;var filePath = "D:\\tmp\\" + fileName;//File.Create(filePath)using (var stream = File.Create(filePath)){if (attachment is MessagePart rfc822){rfc822.Message.WriteTo(stream);}else{part.Content.DecodeTo(stream);}}// 保存附件到本地文件var mailFileInfo = new FileInfo(filePath);}}//附件end}imapClient.Disconnect(true);}}}
}
运行截图: