为 ASP.NET Core 项目添加电子邮件发送功能,可以使用 Microsoft 提供的 NuGet 包 'Microsoft.AspNetCore.Mvc.Core” 和 'MailKit”。 首先,在项目中安装这两个 NuGet 包:
Install-Package Microsoft.AspNetCore.Mvc.Core
Install-Package MailKit
然后添加以下代码:
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
public class EmailSender
{
private readonly string _host;
private readonly int _port;
private readonly bool _enableSsl;
private readonly string _username;
private readonly string _password;
private readonly string _from;
public EmailSender(string host, int port, bool enableSsl, string username, string password, string from)
{
_host = host;
_port = port;
_enableSsl = enableSsl;
_username = username;
_password = password;
_from = from;
}
public async Task SendEmailAsync(string to, string subject, string message)
{
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress("", _from));
emailMessage.To.Add(new MailboxAddress("", to));
emailMessage.Subject = subject;
emailMessage.Body = new TextPart("html")
{
Text = message
};
using (var client = new SmtpClient())
{
await client.ConnectAsync(_host, _port, SecureSocketOptions.StartTls);
await client.AuthenticateAsync(_username, _password);
await client.SendAsync(emailMessage);
await client.DisconnectAsync(true);
}
}
}
然后您可以在控制器中使用它:
[ApiController]
[Route("[controller]")]
public class MyController : ControllerBase
{
private readonly EmailSender _emailSender;
public MyController(EmailSender emailSender)
{
_emailSender = emailSender;
}
[HttpPost]
public async Task Post([FromBody] MyModel model)
{
// do something with model
await _emailSender.SendEmailAsync("recipient@example.com", "Subject line", "Body text");
return Ok();
}
}
请注意,此示例需要从配置文件中读取密码和其他敏感信息。您可以使用 ASP.NET Core 的配置系统来实现。
上一篇:ASP.NETCoreWebAPItrycatchexception问题
下一篇:ASP.NETCoreWebAPIwithEntityFrameworkCore7code-first--忽略的基类属性在序列化时仍会显示出来