MailKit
Getting Started
Sending Messages
One of the more common operations that MailKit is meant for is sending email messages.
using System; using MailKit.Net.Smtp; using MailKit; using MimeKit; namespace TestClient { class Program { public static void Main (string[] args) { var message = new MimeMessage (); message.From.Add (new MailboxAddress ("Joey Tribbiani", "joey@friends.com")); message.To.Add (new MailboxAddress ("Mrs. Chanandler Bong", "chandler@friends.com")); message.Subject = "How you doin'?"; message.Body = new TextPart ("plain") { Text = @"Hey Chandler, I just wanted to let you know that Monica and I were going to go play some paintball, you in? -- Joey" }; using (var client = new SmtpClient ()) { // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS) client.ServerCertificateValidationCallback = (s,c,h,e) => true; client.Connect ("smtp.friends.com", 587, false); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove ("XOAUTH2"); // Note: only needed if the SMTP server requires authentication client.Authenticate ("joey", "password"); client.Send (message); client.Disconnect (true); } } } }
Retrieving Messages (via Pop3)
One of the other main uses of MailKit is retrieving messages from pop3 servers.
using System; using MailKit.Net.Pop3; using MailKit; using MimeKit; namespace TestClient { class Program { public static void Main (string[] args) { using (var client = new Pop3Client ()) { // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS) client.ServerCertificateValidationCallback = (s,c,h,e) => true; client.Connect ("pop.friends.com", 110, false); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove ("XOAUTH2"); client.Authenticate ("joey", "password"); for (int i = 0; i < client.Count; i++) { var message = client.GetMessage (i); Console.WriteLine ("Subject: {0}", message.Subject); } client.Disconnect (true); } } } }
Using IMAP
More important than POP3 support is the IMAP support. Here's a simple use-case of retreiving messages from an IMAP server:
using System; using MailKit.Net.Imap; using MailKit.Search; using MailKit; using MimeKit; namespace TestClient { class Program { public static void Main (string[] args) { using (var client = new ImapClient ()) { // For demo-purposes, accept all SSL certificates client.ServerCertificateValidationCallback = (s,c,h,e) => true; client.Connect ("imap.friends.com", 993, true); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove ("XOAUTH2"); client.Authenticate ("joey", "password"); // The Inbox folder is always available on all IMAP servers... var inbox = client.Inbox; inbox.Open (FolderAccess.ReadOnly); Console.WriteLine ("Total messages: {0}", inbox.Count); Console.WriteLine ("Recent messages: {0}", inbox.Recent); for (int i = 0; i < inbox.Count; i++) { var message = inbox.GetMessage (i); Console.WriteLine ("Subject: {0}", message.Subject); } client.Disconnect (true); } } } }
However, you probably want to do more complicated things with IMAP such as fetching summary information so that you can display a list of messages in a mail client without having to first download all of the messages from the server:
foreach (var summary in inbox.Fetch (0, -1, MessageSummaryItems.Full | MessageSummaryItems.UniqueId)) { Console.WriteLine ("[summary] {0:D2}: {1}", summary.Index, summary.Envelope.Subject); }
The results of a Fetch command can also be used to download individual MIME parts rather than downloading the entire message. For example:
foreach (var summary in inbox.Fetch (0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure)) { if (summary.TextBody != null) { // this will download *just* the text/plain part var text = inbox.GetBodyPart (summary.UniqueId, summary.TextBody); } if (summary.HtmlBody != null) { // this will download *just* the text/html part var html = inbox.GetBodyPart (summary.UniqueId, summary.HtmlBody); } // if you'd rather grab, say, an image attachment... it might look something like this: if (summary.Body is BodyPartMultipart) { var multipart = (BodyPartMultipart) summary.Body; var attachment = multipart.BodyParts.OfType<BodyPartBasic> ().FirstOrDefault (x => x.FileName == "logo.jpg"); if (attachment != null) { // this will download *just* the attachment var part = inbox.GetBodyPart (summary.UniqueId, attachment); } } }
You may also be interested in sorting and searching...
// let's search for all messages received after Jan 12, 2013 with "MailKit" in the subject... var query = SearchQuery.DeliveredAfter (DateTime.Parse ("2013-01-12")) .And (SearchQuery.SubjectContains ("MailKit")).And (SearchQuery.Seen); foreach (var uid in inbox.Search (query)) { var message = inbox.GetMessage (uid); Console.WriteLine ("[match] {0}: {1}", uid, message.Subject); } // let's do the same search, but this time sort them in reverse arrival order var orderBy = new [] { OrderBy.ReverseArrival }; foreach (var uid in inbox.Search (query, orderBy)) { var message = inbox.GetMessage (uid); Console.WriteLine ("[match] {0}: {1}", uid, message.Subject); } // you'll notice that the orderBy argument is an array... this is because you // can actually sort the search results based on multiple columns: orderBy = new [] { OrderBy.ReverseArrival, OrderBy.Subject }; foreach (var uid in inbox.Search (query, orderBy)) { var message = inbox.GetMessage (uid); Console.WriteLine ("[match] {0}: {1}", uid, message.Subject); }
Of course, instead of downloading the message, you could also fetch the summary information for the matching messages or do any of a number of other things with the UIDs that are returned.
How about navigating folders? MailKit can do that, too:
// Get the first personal namespace and list the toplevel folders under it. var personal = client.GetFolder (client.PersonalNamespaces[0]); foreach (var folder in personal.GetSubfolders (false)) Console.WriteLine ("[folder] {0}", folder.Name);
If the IMAP server supports the SPECIAL-USE or the XLIST (GMail) extension, you can get ahold of the pre-defined All, Drafts, Flagged (aka Important), Junk, Sent, Trash, etc folders like this:
if ((client.Capabilities & (ImapCapabilities.SpecialUse | ImapCapabilities.XList)) != 0) { var drafts = client.GetFolder (SpecialFolder.Drafts); } else { // maybe check the user's preferences for the Drafts folder? }
In cases where the IMAP server does not support the SPECIAL-USE or XLIST extensions, you'll have to come up with your own heuristics for getting the Sent, Drafts, Trash, etc folders. For example, you might use logic similar to this:
static string[] CommonSentFolderNames = { "Sent Items", "Sent Mail", /* maybe add some translated names */ }; static IFolder GetSentFolder (ImapClient client, CancellationToken cancellationToken) { var personal = client.GetFolder (client.PersonalNamespaces[0]); foreach (var folder in personal.GetSubfolders (false, cancellationToken)) { foreach (var name in CommonSentFolderNames) { if (folder.Name == commonName) return folder; } } return null; }
Using LINQ, you could simplify this down to something more like this:
static string[] CommonSentFolderNames = { "Sent Items", "Sent Mail", /* maybe add some translated names */ }; static IFolder GetSentFolder (ImapClient client, CancellationToken cancellationToken) { var personal = client.GetFolder (client.PersonalNamespaces[0]); return personal.GetSubfolders (false, cancellationToken).FirstOrDefault (x => CommonSentFolderNames.Contains (x.Name)); }
Another option might be to allow the user of your application to configure which folder he or she wants to use as their Sent folder, Drafts folder, Trash folder, etc.
How you handle this is up to you.
Donate
MailKit is a personal open source project that I have put thousands of hours into perfecting with the goal of making it not only the very best email framework for .NET, but the best email framework for any programming language. I need your help to achieve this.
https://components.xamarin.com/gettingstarted/mailkit
相关推荐
NETCore.MailKit 用于asp.net核心的MailKit扩展 用nuget安装 Install-Package NETCore.MailKit -Version 2.0.3 使用.NET CLI安装 dotnet add package NETCore.MailKit --version 2.0.3 如何使用 在启动时添加...
"Vue.NetCore-master_volvue_vue.netcore_vue.netcore_vol_volnetcore"这个标题可能指的是一个项目,该项目结合了Vue.js和.NET Core,用于前端和后端的开发。"master"通常表示这是项目的主要分支,意味着是最稳定或...
.netcore项目sap的rfc调用所需的sap组件。.netcore调用rfc需要使用SapNwRfc,开发环境需要SAP NetWeaver RFC Library 7.50 SDK引用。SapNwRfc使用请参考:https://github.com/huysentruitw/SapNwRfc
《.NetCore与Petapoco ORM:T4模板在Sqlserver环境中的应用》 在现代软件开发中,ORM(对象关系映射)框架扮演着重要的角色,它将数据库操作抽象化,使得开发者可以使用面向对象的方式处理数据。.NetCore是微软推出...
Vue.NETCORE前后端分离快速开发框架是一个现代的Web应用程序开发工具包,它结合了Vue.js前端框架和.NET Core后端框架,旨在简化和加速开发过程。这个框架利用了前后端分离的概念,允许开发者独立地处理前端用户体验...
asp.netCore3.1+微信登录 WechatHelper 是主要代码。第1步:请求code(前端) 第2步:前端通过获取的code请求API获取access_token(第2步之后都是后台API写代码) 第3步:API通过access_token调用接口 第4步:获取...
《Learun.NetCore:深度探索二次开发平台的精髓》 Learun.NetCore-master.zip是一个包含Learun核心二次开发平台源代码的压缩文件,它为我们提供了一个深入理解.NET Core框架下的应用开发和扩展性的宝贵资源。在这个...
这个名为"基于.netcore搜索封装ElasticSearch.zip"的压缩包,显然包含了一个针对.NET Core平台的Elasticsearch客户端库,方便开发者在.NET Core应用中集成和操作Elasticsearch。 Elasticsearch是一个开源的分布式...
.net c# .netcore 视频解码源程序 基于ffmpeg rtsp rtmp 摄像头实时解码,实时播放 控制 存储,转换 源码 海康 合普 大华等摄像头的实时转码 实时播放,格式转换 core 跨平台
基于C#.NetCore+Vue框架通用管理系统(多数据库SQL+支持VUE3+丰富的表单).zip
"Zxw.Framework.NetCore-dev" 是一个针对C#开发的.NET Core框架,它主要针对Visual Studio Code(VSCode)用户设计,集成了MVC(Model-View-Controller)架构,用于构建高效、可扩展的Web应用程序。这个框架可能是...
基于.NetCore3.1搭建webapi框架。涉及知识有: 1.swagger API接口文档生成 2.多层(包含接口调用方式)高性能数据处理结构 3.数据仓储模式的实现 4.JWT token身份授权验证 5.appsetting.json文件集成读取配置
1、ASP.NETCore WebAPI使用Swagger,使用Cookie持久化存储Token,解决每次刷新需要重新输入Token授权。 2、包含进入swagger首页前,需要进行登录的login.html前台静态页面。 Swagger是一个规范且完整的框架,用于...
标题 "WinSW.NETCore.x64.zip" 暗示我们正在处理一个针对Windows平台的、基于.NET Core的64位服务包装工具,名为WinSW。这个工具的主要目的是帮助用户将可执行文件作为Windows服务来运行,使得应用程序在系统启动时...
.NetCore实现微信订阅号自动回复功能
Aspose.Words 是一款先进的类库,使您可以直接在各个应用程序中执行各种文档处理任务。Aspose.Words 支持 DOC,OOXML,RTF,...使用 Aspose.Words,您可以生成,更改,转换,渲染和打印文档而不使用 Microsoft Word。
.NetCore3.1官方注释汉化补丁 内附加 使用说明 Microsoft.NETCore.App.Ref Microsoft.WindowsDesktop.App.Ref NETStandard.Library.Ref
Vue + C#.NetCore前后端分离,不一样的快速开发框架(提供Vue2/Vue3版本) 框架核心 快速开发(基础功能全部由代码生成器生成) 支持前端、后台自定义业务代码扩展,后台提供了大量常用扩展与通用类 前端、后台提供了近...
Minio .NetCore上传图片且注册服务 操作文档
【标题】:“毕业设计:基于asp.netCore+EFCore+mysql+layui的CRM系统” 【描述】:“计算机毕设源码”通常是指学生在完成计算机科学或相关专业学业时,进行的一项综合性的项目,旨在应用所学理论知识解决实际问题...