這篇文章主要介紹了.NET使用MailKit進(jìn)行郵件處理的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
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是最流行且最強(qiáng)大的.NET郵件處理框架之一,下面為大家簡單介紹MailKit的使用方式(IMAP為例)
1. 參考資料
Github https://github.com/jstedfast/MailKit
官方Doc http://www.mimekit.net/docs/html/Introduction.htm
2.核心內(nèi)容(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);
讀取文件
讀取方式一:可以預(yù)先篩選郵件
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);
郵件操作
操作郵件一:讀取郵件標(biāo)題
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);
}
}
操作郵件四:移動(dòng)郵件(移動(dòng)至刪除文件夾)
client.Inbox.MoveTo(uid, client.GetFolder(SpecialFolder.Trash));
操作郵件五:刪除郵件 - 將郵件標(biāo)記為刪除、最后刪除
client.Inbox.AddFlags(uid, MessageFlags.Deleted, true);
client.Inbox.Expunge();
3.樣例源碼地址
https://github.com/Impartsoft/Bins/tree/main/MailKitDemo
到此這篇關(guān)于.NET使用MailKit進(jìn)行郵件處理的方法步驟的文章就介紹到這了,更多相關(guān).NET MailKit郵件處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
來源:腳本之家
鏈接:https://www.jb51.net/article/205222.htm
申請創(chuàng)業(yè)報(bào)道,分享創(chuàng)業(yè)好點(diǎn)子。點(diǎn)擊此處,共同探討創(chuàng)業(yè)新機(jī)遇!