Asp.Net Core MailKit发送邮件
时间: 2024-05-16 20:15:59 浏览: 230
Asp.net邮件发送
要在 ASP.NET Core 中使用 MailKit 发送电子邮件,需要执行以下步骤:
1. 安装 MailKit 和 MimeKit NuGet 包。
2. 在 Startup.cs 文件中添加以下代码:
```csharp
using MailKit.Net.Smtp;
using MimeKit;
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddMailKit(optionBuilder =>
{
optionBuilder.UseSmtp("smtp.gmail.com", 587);
optionBuilder.EnableSsl = true;
optionBuilder.AuthenticationOptions =
AuthenticationOptions.DoNotAuthenticate;
});
// ...
}
```
3. 在控制器或服务中注入 `IMailer` 接口。
```csharp
using MailKit.Net.Smtp;
using MimeKit;
public class MyController : Controller
{
private readonly IMailer _mailer;
public MyController(IMailer mailer)
{
_mailer = mailer;
}
public async Task<IActionResult> SendEmail()
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress("From Name", "from@example.com"));
message.To.Add(new MailboxAddress("To Name", "to@example.com"));
message.Subject = "Test Email";
message.Body = new TextPart("plain")
{
Text = "This is a test email."
};
await _mailer.SendAsync(message);
return Ok();
}
}
```
4. 通过 MailKit 发送电子邮件:
```csharp
using MailKit.Net.Smtp;
using MimeKit;
public interface IMailer
{
Task SendAsync(MimeMessage message);
}
public class Mailer : IMailer
{
private readonly SmtpClient _smtpClient;
public Mailer(SmtpClient smtpClient)
{
_smtpClient = smtpClient;
}
public async Task SendAsync(MimeMessage message)
{
await _smtpClient.SendAsync(message);
}
}
```
现在,当执行 `SendEmail()` 方法时,将通过 MailKit 发送电子邮件。
阅读全文