.NET Core 下收發郵件之 MailKit

利用代碼發送郵件在工作中還是比較常見的,相信大家都用過SmtpClient來處理髮送郵件的操作,不過這個類以及被標記已過時,所以介紹一個微軟推薦的庫MailKit來處理。

MailKit開源地址:https://github.com/jstedfast/MailKit

新建一個控制檯應用程序,將MailKit添加到項目中。

Install-Package MailKit

新建一個IEmail接口。

using MimeKit;
using System.Threading.Tasks;

namespace EmailDemo
{
    public interface IEmail
    {
        /// <summary>
        /// 發送Email
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        Task SendEmailAsync(MimeMessage message);
    }
}

然後添加Email.cs實現這個接口。

using MailKit.Net.Smtp;
using MimeKit;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace EmailDemo
{
    public class Email : IEmail
    {
        public async Task SendEmailAsync(MimeMessage message)
        {
            var host = "smtp.exmail.qq.com";
            var port = 465;
            var useSsl = true;
            var from_username = "[email protected]";
            var from_password = "...";
            var from_name = "測試";
            var from_address = "[email protected]";

            var address = new List<MailboxAddress>
            {
                new MailboxAddress("111","[email protected]"),
                new MailboxAddress("222","[email protected]")
            };

            message.From.Add(new MailboxAddress(from_name, from_address));
            message.To.AddRange(address);

            using var client = new SmtpClient
            {
                ServerCertificateValidationCallback = (s, c, h, e) => true
            };
            client.AuthenticationMechanisms.Remove("XOAUTH2");

            await client.ConnectAsync(host, port, useSsl);
            await client.AuthenticateAsync(from_username, from_password);
            await client.SendAsync(message);
            await client.DisconnectAsync(true);
        }
    }
}

上面關於郵箱的賬號密碼服務器可以放在配置文件中,這裏爲了方便直接寫了,演示了發送郵件到兩個Email地址。

然後在Program.cs中使用依賴注入的方式調用。

using Microsoft.Extensions.DependencyInjection;
using MimeKit;
using System;
using System.Threading.Tasks;

namespace EmailDemo
{
    class Program
    {
        static async Task Main(string[] args)
        {
            IServiceCollection service = new ServiceCollection();

            service.AddSingleton<IEmail, Email>();

            var provider = service.BuildServiceProvider().GetRequiredService<IEmail>();

            var message = new MimeMessage
            {
                Subject = "我是郵件主題",
                Body = new BodyBuilder
                {
                    HtmlBody = $"我是郵件內容,時間:{DateTime.Now:yyyy-MM-dd HH:mm:ss}"
                }.ToMessageBody()
            };

            await provider.SendEmailAsync(message);
        }
    }
}

以上演示了在 .NET Core 中發送郵件的示例,同時利用MailKit也可以接收郵件,這裏使用場景不多,如有需要可以參考MailKitGitHub代碼示例。

通常發送郵件可以提前寫好HTML模板,然後將關鍵內容做字符串替換,這樣發出去的就是一個比較美觀的郵件了。

MailKit還支持將圖片作爲數據內容發送出去。

using Microsoft.Extensions.DependencyInjection;
using MimeKit;
using MimeKit.Utils;
using System;
using System.Threading.Tasks;

namespace EmailDemo
{
    class Program
    {
        static async Task Main(string[] args)
        {
            IServiceCollection service = new ServiceCollection();

            service.AddSingleton<IEmail, Email>();

            var provider = service.BuildServiceProvider().GetRequiredService<IEmail>();

            var path = "D:\\bg.jpg";

            var builder = new BodyBuilder();

            var image = builder.LinkedResources.Add(path);
            image.ContentId = MimeUtils.GenerateMessageId();

            builder.HtmlBody = $"當前時間:{DateTime.Now:yyyy-MM-dd HH:mm:ss} <img src=\"cid:{image.ContentId}\"/>";

            var message = new MimeMessage
            {
                Subject = "帶圖片的郵件推送",
                Body = builder.ToMessageBody()
            };

            await provider.SendEmailAsync(message);
        }
    }
}

先在本地準備一張圖片,利用ContentId的方式嵌入在img標籤中,成功將其發送出去。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章