.NET使用MailKit進行郵件處理

Iannnnnnnnnnnnn發表於2021-02-01

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

相關文章