14

如何在 Asp.Net Core 中发送 Email

 3 years ago
source link: https://mp.weixin.qq.com/s?__biz=MjM5MjQwMDUzMw%3D%3D&%3Bmid=2247484161&%3Bidx=1&%3Bsn=7328bd1052fb5bfd6038abcc8a2fb634
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在项目开发中常常会需要做发送 Email 的功能,在 ASP.NET Core 中你可以用 MailKit 来实现 Email 的发送, MailKit 是一个开源的客户端库,可用在 Windows,Linux 或者 Mac 上,本篇文章就来讨论在 ASP.NET Core 中去实现。

安装 MailKit

要想使用 MailKit,你可以使用 Visual Studio 2019 中的 NuGet package manager 可视化界面进行安装,或者通过 NuGet package manager console 命令行输入如下命令:


Install-Package NETCore.MailKit

安装完成之后,在代码中引入以下命令空间即可。


using MailKit.Net.Smtp;
using MimeKit;

配置 Email 的基础信息

下面的代码片段展示了在 appsettings.json 文件中配置 email 的详细信息。


"NotificationMetadata": {
"Sender": "[email protected]",
"SmtpServer": "smtp.gmail.com",
"Reciever": "[email protected]",
"Port": 465,
"Username": "[email protected]",
"Password": "specify your password here"
}

为了能够实现 configuration 中的NotificationMetadata节点映射,我定义了一个 NotificationMetadata 类,代码如下:


public class NotificationMetadata
{
public string Sender { get; set; }
public string Reciever { get; set; }
public string SmtpServer { get; set; }
public int Port { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}

接下来在 Startup.ConfigureServices 方法中将 NotificationMetadata 节点映射到 NotificationMetadata 类。


public void ConfigureServices(IServiceCollection services)
{
var notificationMetadata =
Configuration.GetSection("NotificationMetadata").
Get<NotificationMetadata>();
services.AddSingleton(notificationMetadata);
services.AddControllers();
}

生成 EmailMessage 消息类

使用如下代码创建一个 EmailMessage 类。


public class EmailMessage
{
public MailboxAddress Sender { get; set; }
public MailboxAddress Reciever { get; set; }
public string Subject { get; set; }
public string Content { get; set; }
}

生成 MimeMessage 类

下面的代码展示了如何从自定义的 EmailMessage 类中构造出一个 MimeMessage。


private MimeMessage CreateMimeMessageFromEmailMessage(EmailMessage message)
{
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(message.Sender);
mimeMessage.To.Add(message.Reciever);
mimeMessage.Subject = message.Subject;
mimeMessage.Body = new TextPart(MimeKit.Text.TextFormat.Text)
{ Text = message.Content };
return mimeMessage;
}

用 MailKit 同步发送 Email

为了最终能够实现 email 发送,需要使用 MailKit.Net.Smtp 命名空间下的 SmtpClient 类,下面的代码展示了具体实现步骤。


using (SmtpClient smtpClient = new SmtpClient())
{
smtpClient.Connect(_notificationMetadata.SmtpServer,
_notificationMetadata.Port, true);
smtpClient.Authenticate(_notificationMetadata.UserName,
_notificationMetadata.Password);
smtpClient.Send(mimeMessage);
smtpClient.Disconnect(true);
}

为了方便起见,我就把完整的发送 Email 代码放在 DefaultController.Get 方法下。


public string Get()
{
EmailMessage message = new EmailMessage();
message.Sender = new MailboxAddress("Self", _notificationMetadata.Sender);
message.Reciever = new MailboxAddress("Self", _notificationMetadata.Reciever);
message.Subject = "Welcome";
message.Content = "Hello World!";
var mimeMessage = CreateEmailMessage(message);
using (SmtpClient smtpClient = new SmtpClient())
{
smtpClient.Connect(_notificationMetadata.SmtpServer,
_notificationMetadata.Port, true);
smtpClient.Authenticate(_notificationMetadata.UserName,
_notificationMetadata.Password);
smtpClient.Send(mimeMessage);
smtpClient.Disconnect(true);
}
return "Email sent successfully";
}

用 MailKit 异步发送 Email

上面我们用同步的方式发送 Email,这一节来看看如何使用异步的方式发送 Email。


using (SmtpClient smtpClient = new SmtpClient())
{
await smtpClient.ConnectAsync(_notificationMetadata.SmtpServer,
_notificationMetadata.Port, true);
await smtpClient.AuthenticateAsync(_notificationMetadata.UserName,
_notificationMetadata.Password);
await smtpClient.SendAsync(mimeMessage);
await smtpClient.DisconnectAsync(true);
}

最后值得注意的是,MailKit 除了简单的字符串,还支持模板的方式甚至可以带上 附件 发送,更多的 MailKit 特性我会在后面的文章中和大家去讨论。

译文链接:https://www.infoworld.com/article/3534690/how-to-send-emails-in-aspnet-core.html

喜欢就来个三连,让更多人因你而受益


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK