Exemplo n.º 1
0
        public EmailNotificatorTests()
        {
            _smtpClientFactory  = Substitute.For <ISmtpClientFactory>();
            _mailSettingsConfig = MailSettingsConfigFake.Generate();

            _mailMessageFactory = Substitute.For <IMessageFactory <MailMessageCreateRequest, MailMessage> >();
            _notificator        = new EmailNotificator(_smtpClientFactory, _mailSettingsConfig, _mailMessageFactory);

            var recipients = new List <string>()
            {
                _faker.Internet.Email(),
            };

            _emailMessage = new EmailMessage("from", recipients, "subject", "body");

            var smtpServerConfig1 = SmtpServerConfigFake.Generate();
            var smtpServerConfig2 = SmtpServerConfigFake.Generate();
            var smtpServerConfig3 = SmtpServerConfigFake.Generate();

            _mailSettingsConfig.Smtp.Servers = new List <SmtpServerConfig>()
            {
                smtpServerConfig1, smtpServerConfig2, smtpServerConfig3
            };

            _smtpClient1 = Substitute.ForPartsOf <FakeSmtpClient>(smtpServerConfig1.Host);
            _smtpClient2 = Substitute.ForPartsOf <FakeSmtpClient>(smtpServerConfig2.Host);
            _smtpClient3 = Substitute.ForPartsOf <FakeSmtpClient>(smtpServerConfig3.Host);

            _smtpClientFactory.Create(smtpServerConfig1).Returns(_smtpClient1);
            _smtpClientFactory.Create(smtpServerConfig2).Returns(_smtpClient2);
            _smtpClientFactory.Create(smtpServerConfig3).Returns(_smtpClient3);
        }
Exemplo n.º 2
0
        public void Send_Should_ThrowSmptClientException_When_ClientThrowArgumentException()
        {
            var client = Substitute.For <ISmtpClient>();

            client.When(c => c.Send(Arg.Any <MailMessage>())).Do(info => throw new ArgumentException());

            _clientFactory.Create().Returns(client);

            Expect(() => _mailSender.Send(Arg.Any <MailMessage>()), Throws.TypeOf <SmptClientException>());
        }
Exemplo n.º 3
0
        public Mailer(IOptionsMonitor <SmtpConfig> smtpConfigOptions, ISmtpClientFactory smtpClientFactory)
        {
            SmtpConfig smtpConfig = smtpConfigOptions.CurrentValue;

            _smptClient = smtpClientFactory.Create(smtpConfig);
            _sender     = smtpConfig.Email;
        }
Exemplo n.º 4
0
 public async Task SendEmail(string body)
 {
     var client      = _smtpClientFactory.Create(Constants.Host, Constants.Port, Constants.UserName, Constants.Password);
     var mailMessage = _mailMessageFactory.Create(Constants.From, Constants.To, Constants.Subject,
                                                  $"{Constants.Body}{body}");
     await client.SendMailAsync(mailMessage);
 }
Exemplo n.º 5
0
        /// <summary>
        /// Sends an email message
        /// </summary>
        /// <param name="emailMessage">The email message to be sent</param>
        /// <returns>A Task for awaiting</returns>
        public async Task Send(EmailMessage emailMessage)
        {
            if (emailMessage == null)
            {
                throw new ArgumentNullException(nameof(emailMessage), "The email message cannot be null");
            }

            _logger.LogDebug("Attempting to send an email {@emailMessage}", emailMessage);

            var message = CreateMimeMessage(emailMessage);
            var useSSL  = true;
            var oAuth2AuthenticationType = "XOAUTH2";

            using (var emailClient = _smptClientFactory.Create())
            {
                //emailClient.ServerCertificateValidationCallback = (s, c, ch, ssl) => true; //Need to implement better validation

                await emailClient.ConnectAsync(_emailConfiguration.Server, _emailConfiguration.Port, useSSL);

                emailClient.AuthenticationMechanisms.Remove(oAuth2AuthenticationType);

                await emailClient.AuthenticateAsync(_emailConfiguration.Username, _emailConfiguration.Password);

                await emailClient.SendAsync(message);

                await emailClient.DisconnectAsync(true);
            }

            _logger.LogDebug("Email successfully sent {@emailMessage}", emailMessage);
        }
Exemplo n.º 6
0
        public void Send(MailMessage mailMessage)
        {
            _validator.Validate(mailMessage);

            ISmtpClient client = null;

            try
            {
                client = _factory.Create();
                SetUpClient(client);

                client.Send(mailMessage);
            }
            catch (ArgumentException e)
            {
                throw new SmptClientException("Cannot setup client.", e);
            }
            catch (InvalidOperationException e)
            {
                throw new SmptClientException("Client cannot do operation.", e);
            }
            catch (SmtpException e)
            {
                throw new SmptClientException("Client cannot send mail message.", e);
            }
            finally
            {
                client?.Dispose();
            }
        }
Exemplo n.º 7
0
        void processMail(CancellationToken token)
        {
            if (_mailsActiveCount > _maxParallelMessages)
            {
                return;
            }

            Interlocked.Increment(ref _mailsActiveCount);
            QueuedMail msg = null;

            try {
                if (!token.IsCancellationRequested && _mainQueue.TryDequeue(out msg))
                {
                    DateTime dt = DateTime.UtcNow;
                    using (ISmpClient cli = _clifac.Create())
                    {
                        cli.Send(msg.Msg);
                    }

                    if ((DateTime.UtcNow - dt).TotalSeconds > WarnTimeInSec)
                    {
                        _logger.Warn("Sending mail '{0}', to {1} took extratime: {2}s", msg.Msg.Subject, msg.Msg.Recipients, (DateTime.UtcNow - dt).TotalSeconds);
                    }

                    msg.Msg.Dispose();
                }
            }
            catch (Exception ex)
            {
                _logger.Exception(string.Format("On sending news, queue size = {0}", _mainQueue.Count), ex);
                if (!token.IsCancellationRequested)
                {
                    msg.LastError = ex;
                    _retryQueue.Enqueue(msg);
                    startRetrying();
                }
            }
            finally {
                Interlocked.Decrement(ref _mailsActiveCount);
            }

            if (_mainQueue.Count > 0 && !token.IsCancellationRequested)
            {
                startSending();
            }
        }
Exemplo n.º 8
0
        private async Task <IOutcome> SendOverMultipleSmtpServersAsync(EmailMessage message)
        {
            var errors = new List <string>();
            var smtpServerConfigurations = _mailSettingsConfig.Smtp.Servers;
            var wasSentSuccessfully      = false;

            foreach (var smtpServerConfiguration in smtpServerConfigurations)
            {
                try
                {
                    if (wasSentSuccessfully)
                    {
                        continue;
                    }

                    var createRequest = new MailMessageCreateRequest()
                    {
                        EmailMessage           = message,
                        SmtpServerConfig       = smtpServerConfiguration,
                        IsReadSenderFromConfig = true,
                        RequiredRecipients     = _mailSettingsConfig.Smtp.RequiredRecipients,
                    };
                    var mailMessage = await _mailMessageFactory.CreateAsync(createRequest);

                    using (var smtpClient = _smtpClientFactory.Create(smtpServerConfiguration))
                    {
                        await smtpClient.SendAsync(mailMessage);

                        wasSentSuccessfully = true;
                    }
                }
                catch (Exception ex)
                {
                    wasSentSuccessfully = false;

                    var error = ex.Message;
                    if (ex.InnerException != null)
                    {
                        var innerEx = ex.InnerException;
                        while (innerEx.InnerException != null)
                        {
                            innerEx = innerEx.InnerException;
                        }

                        error = innerEx.Message;
                    }

                    errors.Add($"SMTP {smtpServerConfiguration.Host} throw an error: {error}");
                }
            }

            if (wasSentSuccessfully)
            {
                return(Outcomes.Success());
            }

            return(Outcomes.Failure().WithMessagesFrom(errors.Distinct()));
        }
Exemplo n.º 9
0
 public void Send(MailMessage message)
 {
     using (var client = factory.Create())
     {
         using (message)
         {
             client.Send(message);
         }
     }
 }
Exemplo n.º 10
0
        public void Send(MailerConfig config, Notification notification)
        {
            var client = _smtpFactory.Create(config.Host, config.Port);

            client.Credentials = new NetworkCredential(config.UserName, config.Password);
            client.EnableSsl   = config.EnableSsl;

            using (var message = new MailMessage(config.From, config.To))
            {
                message.Subject = notification.Title;
                message.Body    = notification.Message;

                client.Send(message);
            }
        }