Ejemplo n.º 1
0
        public async void SendEmail()
        {
            var recipients = new List <string> {
                "*****@*****.**"
            };
            var report = new SolarAndUtilityReport(new DateInterval(new LocalDate(2017, 07, 17), new LocalDate(2017, 08, 16)), 100, 0, 2000);

            var expectedMessage = new MimeMessage
            {
                Subject = "expected message"
            };

            A.CallTo(() => reportFormatter.FormatReport(A <SolarAndUtilityReport> ._)).Returns(expectedMessage);

            await emailSender.SendEmail(report, recipients);

            CancellationToken cancellationToken = default;

            A.CallTo(() => smtpClient.ConnectAsync("aldaviva.com", 25, SecureSocketOptions.StartTls, cancellationToken))
            .MustHaveHappened()
            .Then(A.CallTo(() => smtpClient.AuthenticateAsync("user", "pass", cancellationToken)).MustHaveHappened())
            .Then(A.CallTo(() => smtpClient.SendAsync(A <MimeMessage> .That.Matches(message =>
                                                                                    message.Subject == "expected message"), cancellationToken, default)).MustHaveHappened())
            .Then(A.CallTo(() => smtpClient.DisconnectAsync(true, cancellationToken)).MustHaveHappened());
        }
        private async Task SendEmailAsync(IMailTransport transport, IEnumerable <MimeMessage> messages)
        {
            try
            {
                foreach (var message in messages.ToList())
                {
                    transport.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    await transport.ConnectAsync(
                        Settings.Default.Host,
                        Settings.Default.Port,
                        SecureSocketOptions.Auto).ConfigureAwait(false);

                    transport.AuthenticationMechanisms.Remove("XOAUTH2");

                    await transport.AuthenticateAsync(
                        Settings.Default.Login,
                        Settings.Default.Password).ConfigureAwait(false);

                    await transport.SendAsync(message).ConfigureAwait(false);

                    await transport.DisconnectAsync(true).ConfigureAwait(false);
                }
            }
            catch (Exception exception)
            {
                _logger.Error(exception.Message);
            }
        }
        public async Task SendEmailAsync(string email, string subject, string htmlMessage)
        {
            await ConnectAsync(client);

            await client.SendAsync(BuildMail(email, subject, htmlMessage));

            await DisconnectAsync(client);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Asynchronously sends the specified messages.
        /// </summary>
        /// <param name="messages">The collection of messages to send.</param>
        /// <param name="cancellationToken">The token used to cancel an ongoing async operation.</param>
        /// <returns></returns>
        public virtual async Task SendAsync(IEnumerable <MimeMessage> messages, CancellationToken cancellationToken = default)
        {
            IMailTransport client = null;

            try
            {
                client = await CreateOutgoingMailClientAsync(cancellationToken);

                foreach (var message in messages)
                {
                    try
                    {
                        await client.SendAsync(message, cancellationToken);
                        await OnSuccessAsync(message);
                    }
                    catch (Exception ex)
                    {
                        if (Error != null)
                        {
                            await Error(new SendEventArgs(new MimeMessage[] { message }, ex));
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (Error != null)
                {
                    await Error(new SendEventArgs(messages, ex));
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (client != null)
                {
                    client.Disconnect(true);

                    if (client is IDisposable obj)
                    {
                        obj.Dispose();
                    }
                }
            }
        }
        /// <summary>
        /// Sends an e-mail message asynchronously using the
        /// provided <see cref="IMailTransport" /> instance.
        /// </summary>
        /// <param name="emailMessage">The e-mail message to send asynchronously.</param>
        /// <returns>An asynchronous <see cref="Task"/> context.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="emailMessage" /> is
        /// <see langword="null" />.</exception>
        public async Task SendEmailAsync(EmailMessage emailMessage)
        {
            if (emailMessage is null)
            {
                throw new ArgumentNullException(nameof(emailMessage));
            }

            await client.ConnectAsync(settings.Host, settings.Port).ConfigureAwait(false);

            try
            {
                var authentication = settings.Authentication;
                if (authentication.IsRequired)
                {
                    await client.AuthenticateAsync(authentication.UserName, authentication.Password).ConfigureAwait(false);
                }

                var mimeMessage = emailMessage.AsMimeMessage(settings.EmailSubjectPrefix);
                await client.SendAsync(mimeMessage).ConfigureAwait(false);

                logger.LogInformation(
                    "SendEmailAsync: Sent: {server}:{port} with auth required {isRequired} and U:{user}, Sent Message {mimeMessage}",
                    settings.Host,
                    settings.Port,
                    authentication.IsRequired,
                    authentication.UserName,
                    mimeMessage);
            }
            catch (Exception ex)
            {
                logger.LogError(
                    ex,
                    "SendEmailAsync: Failed: {server}:{port} with auth required {isRequired} and U:{user}, Sending Message {@mimeMessage}",
                    settings.Host,
                    settings.Port,
                    settings.Authentication.IsRequired,
                    settings.Authentication.UserName,
                    emailMessage);

                throw;
            }
            finally
            {
                if (client.IsConnected)
                {
                    await client.DisconnectAsync(true).ConfigureAwait(false);
                }
            }
        }
Ejemplo n.º 6
0
        public async Task sendEmail(SolarAndUtilityReport report, IEnumerable <string> recipients)
        {
            MimeMessage message = reportFormatter.formatReport(report);

            message.From.Add(new MailboxAddress("Dad's Energy Reporter", settings.reportSenderEmail));
            message.To.AddRange(recipients.Select(recipient => new MailboxAddress(recipient)));

            try {
                await smtpClient.ConnectAsync(settings.smtpHost, settings.smtpPort, SecureSocketOptions.StartTls);

                await smtpClient.AuthenticateAsync(settings.smtpUsername, settings.smtpPassword);

                await smtpClient.SendAsync(message);

                await smtpClient.DisconnectAsync(true);
            } catch (IOException e) {
                throw new EmailException("Failed to send email message", e);
            }
        }
        public async Task Send(string from, string to, string subject, string body)
        {
            var message = new MimeMessage();

            message.From.Add(MailboxAddress.Parse(from));
            message.To.Add(MailboxAddress.Parse(to));
            message.Subject = subject;
            message.Body    = new TextPart(body);

            await _mailTransport.ConnectAsync(_settings.Host, _settings.Port, _settings.UseSsl);

            if (!string.IsNullOrEmpty(_settings.Username))
            {
                await _mailTransport.AuthenticateAsync(_settings.Username, _settings.Password);
            }

            await _mailTransport.SendAsync(message);

            await _mailTransport.DisconnectAsync(true);
        }