.NET使用MailKit进行邮件处理的方法步骤

时间:2022-09-05 20:40:02

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为例)

连接邮箱

加密

?
1
client.Connect("imap.exmail.qq.com", 993, SecureSocketOptions.SslOnConnect);

不加密

?
1
client.Connect("imap.exmail.qq.com", 143, SecureSocketOptions.None);

登入邮箱

?
1
client.Authenticate(MAIL_NAME, MAIL_PASSWORD);

打开邮件文件夹

?
1
client.Inbox.Open(FolderAccess.ReadWrite);

读取文件

读取方式一:可以预先筛选邮件

?
1
2
3
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);

读取方式二:读取所有邮件

?
1
var uids = client.Inbox.Search(SearchQuery.All);

邮件操作

操作邮件一:读取邮件标题

?
1
2
3
string subject = message.Subject;
  if (!subject.Contains("MimeKitDemo"))
    return;

操作邮件二:读取正文

?
1
2
3
string body = message.TextBody ?? string.Empty;
  if (!body.Contains("MimeKitDemoBody"))
    return;

操作邮件三:下载邮件附件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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);
    }
  }

操作邮件四:移动邮件(移动至删除文件夹)

?
1
client.Inbox.MoveTo(uid, client.GetFolder(SpecialFolder.Trash));

操作邮件五:删除邮件 - 将邮件标记为删除、最后删除

?
1
2
client.Inbox.AddFlags(uid, MessageFlags.Deleted, true);
  client.Inbox.Expunge();

3.样例源码地址

https://github.com/Impartsoft/Bins/tree/main/MailKitDemo

到此这篇关于.NET使用MailKit进行邮件处理的方法步骤的文章就介绍到这了,更多相关.NET MailKit邮件处理内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/Iannnnnnnnnnnnn/p/14359043.html