1. 程式人生 > >asp.net core 2.0 郵件傳送服務

asp.net core 2.0 郵件傳送服務

  網上找了一下,發現一個很不錯的郵件傳送服務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("[email protected]",EmailType.Captcha ,$"驗證碼:{code},如非本人操作請忽略。");
                _logger.LogInformation("傳送郵件,to:"+"[email protected]"+",型別:"+EmailType.Captcha);
                return Content("ok");
            }
            catch (Exception e)
            {
                return Content("出錯了:"+e.Message);
            }
            
        }
    }

 

  收到驗證碼: