.NET使用MailKit進行郵件處理的方法步驟
0.介紹
MimeKit and MailKit are popular fully-featured email frameworks for .NET
框架支持版本如下
Supports .NET 4.5, .NET 4.6, .NET 4.7, .NET 4.8, .NET 5.0, .NETStandard 2.0, Xamarin.Android, Xamarin.iOS, Windows Phone 8.1, and more.
MailKit是最流行且最強大的.NET郵件處理框架之一,下面為大傢簡單介紹MailKit的使用方式(IMAP為例)
1. 參考資料
Github https://github.com/jstedfast/MailKit
官方Doc http://www.mimekit.net/docs/html/Introduction.htm
2.核心內容(IMAP為例)
連接郵箱
加密
client.Connect("imap.exmail.qq.com", 993, SecureSocketOptions.SslOnConnect);
不加密
client.Connect("imap.exmail.qq.com", 143, SecureSocketOptions.None);
登入郵箱
client.Authenticate(MAIL_NAME, MAIL_PASSWORD);
打開郵件文件夾
client.Inbox.Open(FolderAccess.ReadWrite);
讀取文件
讀取方式一:可以預先篩選郵件
search for messages where the Subject header contains either "MimeKit" or "MailKit" var query = SearchQuery.SubjectContains("MimeKit").Or(SearchQuery.SubjectContains("MailKit")); var uids = client.Inbox.Search(query);
讀取方式二:讀取所有郵件
var uids = client.Inbox.Search(SearchQuery.All);
郵件操作
操作郵件一:讀取郵件標題
string subject = message.Subject; if (!subject.Contains("MimeKitDemo")) return;
操作郵件二:讀取正文
string body = message.TextBody ?? string.Empty; if (!body.Contains("MimeKitDemoBody")) return;
操作郵件三:下載郵件附件
var attachments = message.Attachments; if (attachments.Any()) { foreach (var attachment in attachments) DownloadAttachment(attachment); } private static void DownloadAttachment(MimeEntity attachment) { if (attachment is MessagePart) { var fileName = attachment.ContentDisposition?.FileName; var rfc822 = (MessagePart)attachment; if (string.IsNullOrEmpty(fileName)) fileName = "attached-message.eml"; var path = Path.Combine(DIRECTORY, fileName); using (var stream = File.Create(path)) rfc822.Message.WriteTo(stream); } else { var part = (MimePart)attachment; var fileName = part.FileName; var path = Path.Combine(DIRECTORY, fileName); using (var stream = File.Create(path)) part.Content.DecodeTo(stream); } }
操作郵件四:移動郵件(移動至刪除文件夾)
client.Inbox.MoveTo(uid, client.GetFolder(SpecialFolder.Trash));
操作郵件五:刪除郵件 – 將郵件標記為刪除、最後刪除
client.Inbox.AddFlags(uid, MessageFlags.Deleted, true); client.Inbox.Expunge();
3.樣例源碼地址
https://github.com/Impartsoft/Bins/tree/main/MailKitDemo
到此這篇關於.NET使用MailKit進行郵件處理的方法步驟的文章就介紹到這瞭,更多相關.NET MailKit郵件處理內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- Python實現郵件自動下載的示例詳解
- 詳解Python如何實現發送帶附件的電子郵件
- python使用imap-tools模塊下載郵件中的附件的示例
- Python實現自動化郵件發送過程詳解
- Python自動化辦公之郵件發送全過程詳解