网上找了一下,发现一个很不错的邮件发送服务Mailgun,首先要注册Mailgun账号,获得apikey以及domainame;
然后项目中安装nuget:
配置并注册服务:
public interface IEmailSender { Task SendEmailAsync(string email, string subject, string message); }
public class EmailSender:IEmailSender { private readonly EmailSettings _emailSettings; public EmailSender(IOptions<EmailSettings> emailOptions) { _emailSettings = emailOptions.Value; } public Task SendEmailAsync(string account, string subject, string mess) { var domainName = _emailSettings.DomainName; var apiKey = _emailSettings.ApiKey; var sender = new MailgunSender(domainName, apiKey); Email.DefaultSender = sender; var email = Email.From(_emailSettings.From, "XXXXXXX平台") .To(account) .Subject(subject) .Body(mess); return email.SendAsync(); } }
public class EmailSettings { public string ApiKey { get; set; } public string ApiBaseUri { get; set; } public string RequestUri { get; set; } public string From { get; set; } public string DomainName { get; set; } }
#region 注册邮件服务 services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings")); services.AddTransient<IEmailSender, EmailSender>(); #endregion
调用:
public class TestController : Controller { private readonly IOptions<EmailSettings> _emailOptions; private readonly ILogger<TestController> _logger; private readonly IEmailSender _emailSender; public TestController(IOptions<EmailSettings> emailOptions,ILogger<TestController> logger,IEmailSender emailSender) { _emailOptions = emailOptions; _logger = logger; _emailSender = emailSender; } public async Task<IActionResult> Index() { try { string code = "259878"; await _emailSender.SendEmailAsync("3sdaasdadasdad6@qq.com",EmailType.Captcha ,$"验证码:{code},如非本人操作请忽略。"); _logger.LogInformation("发送邮件,to:"+"3asdasdadad6@qq.com"+",类型:"+EmailType.Captcha); return Content("ok"); } catch (Exception e) { return Content("出错了:"+e.Message); } } }
收到验证码: