利用代碼發送郵件在作業中還是比較常見的,相信大家都用過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=https://www.cnblogs.com/"cid:{image.ContentId}/"/>";
var message = new MimeMessage
{
Subject = "帶圖片的郵件推送",
Body = builder.ToMessageBody()
};
await provider.SendEmailAsync(message);
}
}
}
先在本地準備一張圖片,利用ContentId的方式嵌入在img標簽中,成功將其發送出去,

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/52.html
標籤:.NET Core
上一篇:.NET Core 生成二維碼
