Exemplo n.º 1
0
 public EmailService(
     IOptions <EmailServiceOptions> options,
     ILogger <EmailService> logger)
 {
     _options = options.Value;
     _logger  = logger;
 }
Exemplo n.º 2
0
        public async Task <bool> SendByConfigurationData(EmailServiceOptions options, string to, string subject = "", string body = "", string[] cc = null, string[] bcc = null)
        {
            var mailMessage = new MailMessage();

            mailMessage.IsBodyHtml = true;
            if (cc != null)
            {
                foreach (var item in cc)
                {
                    mailMessage.CC.Add(item);
                }
            }

            if (bcc != null)
            {
                foreach (var item in bcc)
                {
                    mailMessage.Bcc.Add(item);
                }
            }

            var emails = to.Split(';');

            foreach (var email in emails)
            {
                if (!string.IsNullOrEmpty(email))
                {
                    mailMessage.To.Add(email);
                }
            }

            mailMessage.Subject = subject;
            mailMessage.Body    = body;

            try
            {
                mailMessage.From = new MailAddress(options.Email, options.Alias);

                var senderUserName = options.Username;
                if (string.IsNullOrEmpty(senderUserName))
                {
                    senderUserName = options.Email;
                }

                var smtpClient = new
                                 SmtpClient(options.Host, options.Port)
                {
                    Credentials =
                        new System.Net.NetworkCredential(senderUserName,
                                                         options.Password),
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    EnableSsl      = options.EnableSsl
                };

                await smtpClient.SendMailAsync(mailMessage);

                return(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, this.GetType().Name);
                return(false);
            }
        }