ASP.NET Core中使用MailKit发送电子邮件是一种常见且灵活的方式。MailKit是一个强大的开源邮件库,可以轻松地集成到ASP.NET Core应用程序中。本文主要介绍在ASP.NET Core 中使用 MailKit 发送邮件的方法及相关示例代码。

1、安装MailKit包

使用 MailKit,需要安装引用 MailKit,安装的方法有多种,分别如下,

1)使用Nuget界面管理器

搜索 "MailKit" 在列表中分别找到它,点击"安装"

相关文档VS(Visual Studio)中Nuget的使用

2)使用Package Manager命令安装

PM> Install-Package MailKit

3)使用.NET CLI命令安装

> dotnet add package MailKit

2、配置SMTP服务器设置

appsettings.json中配置SMTP服务器的设置:

{
  "SmtpSettings": {
    "Server": "smtp.example.com",
    "Port": 587,
    "SenderName": "Your Name",
    "SenderEmail": "your.email@example.com",
    "Username": "your.email@example.com",
    "Password": "yourpassword",
    "UseSsl": true
  }
}

3、创建邮件服务类

创建一个服务类来封装发送邮件的代码如下,

using MailKit.Net.Smtp;
using MimeKit;
using Microsoft.Extensions.Options;

public class SmtpSettings
{
    public string Server { get; set; }
    public int Port { get; set; }
    public string SenderName { get; set; }
    public string SenderEmail { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public bool UseSsl { get; set; }
}

public interface IEmailService
{
    Task SendEmailAsync(string recipientEmail, string subject, string message);
}

public class EmailService : IEmailService
{
    private readonly SmtpSettings _smtpSettings;

    public EmailService(IOptions<SmtpSettings> smtpSettings)
    {
        _smtpSettings = smtpSettings.Value;
    }

    public async Task SendEmailAsync(string recipientEmail, string subject, string message)
    {
        var emailMessage = new MimeMessage();
        emailMessage.From.Add(new MailboxAddress(_smtpSettings.SenderName, _smtpSettings.SenderEmail));
        emailMessage.To.Add(new MailboxAddress("", recipientEmail));
        emailMessage.Subject = subject;

        var bodyBuilder = new BodyBuilder { HtmlBody = message };
        emailMessage.Body = bodyBuilder.ToMessageBody();

        using (var client = new SmtpClient())
        {
            await client.ConnectAsync(_smtpSettings.Server, _smtpSettings.Port, _smtpSettings.UseSsl);

            // Note: only needed if the SMTP server requires authentication
            await client.AuthenticateAsync(_smtpSettings.Username, _smtpSettings.Password);

            await client.SendAsync(emailMessage);
            await client.DisconnectAsync(true);
        }
    }
}

4、 注册邮件服务

Startup.cs中注册邮件服务,使其可以通过依赖注入使用,代码如下,

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<SmtpSettings>(Configuration.GetSection("SmtpSettings"));
    services.AddTransient<IEmailService, EmailService>();

    // 其他服务注册...
}

或者,在Program.cs中,代码如下,

builder.Services.Configure<SmtpSettings>(builder.Configuration.GetSection("SmtpSettings"));
builder.Services.AddTransient<IEmailService, EmailService>();

5、使用邮件服务发送邮件

在控制器或服务中,使用IEmailService发送邮件:

public class HomeController : Controller
{
    private readonly IEmailService _emailService;

    public HomeController(IEmailService emailService)
    {
        _emailService = emailService;
    }

    public async Task<IActionResult> SendTestEmail()
    {
        await _emailService.SendEmailAsync("recipient@example.com", "Test Subject", "<h1>This is a test email</h1>");
        return Ok("Email sent successfully!");
    }
}

推荐文档