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("3sdaasdadasdad6@qq.com",EmailType.Captcha ,$"验证码:{code},如非本人操作请忽略。");
                _logger.LogInformation("发送邮件,to:"+"3asdasdadad6@qq.com"+",类型:"+EmailType.Captcha);
                return Content("ok");
            }
            catch (Exception e)
            {
                return Content("出错了:"+e.Message);
            }
            
        }
    }

 

  收到验证码:

 

转载于:https://www.cnblogs.com/hany-sundigital/p/10030131.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值