コード例 #1
0
        public async Task <bool> SendEmail(EmailMessage message)
        {
            message.Sender = new MailboxAddress(_configuration.SenderName, _configuration.Sender);

            var mimeMessage = CreateMimeMessageFromEmailMessage(message);

            if (mimeMessage == null)
            {
                return(false);
            }

            try
            {
                await _client.ConnectAsync(_configuration.SmtpServer, _configuration.Port, true);

                await _client.AuthenticateAsync(_configuration.UserName, _configuration.Password);

                await _client.SendAsync(mimeMessage);

                await _client.DisconnectAsync(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(false);
            }

            return(true);
        }
コード例 #2
0
        private async Task SendEmailAsync(string email, string subject, string body)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(smtpSettings.MailSenderName, smtpSettings.MailSender));
                message.To.Add(new MailboxAddress(email));
                message.Subject = subject;
                message.Body    = new TextPart("html")
                {
                    Text = body
                };

                using (smtpClient)
                {
                    await smtpClient.ConnectAsync(smtpSettings.SmtpServer, smtpSettings.Port, SecureSocketOptions.StartTls);

                    await smtpClient.AuthenticateAsync(smtpSettings.Username, smtpSettings.Password);

                    await smtpClient.SendAsync(message);

                    await smtpClient.DisconnectAsync(true);
                }
            }
            catch (Exception e)
            {
                logger.LogError(new EventId(2000, "EmailSendError"), e, "");
            }
        }
コード例 #3
0
        private async Task EnvieEmailAsync(MimeMessage mail)
        {
            try{
                await _smtpClient.ConnectAsync(_configuracaoSmtp.Servidor, _configuracaoSmtp.Porta, _configuracaoSmtp.UseSsl).ConfigureAwait(false);

                if (_configuracaoSmtp.RequerAutenticacao)
                {
                    await _smtpClient.AuthenticateAsync(_configuracaoSmtp.Usuario, _configuracaoSmtp.Senha).ConfigureAwait(false);
                }
                await _smtpClient.SendAsync(mail).ConfigureAwait(false);

                await _smtpClient.DisconnectAsync(true).ConfigureAwait(false);
            }
            catch (Exception ex) {
                throw new EnvioDeEmailException("Erro ao enviar o e-mail.", ex.InnerException);
            }
        }
コード例 #4
0
        public async Task Send(string to, string subject, string body, bool isHtmlBody = true)
        {
            var email = CreateEmail(to, subject, body, isHtmlBody);

            await _smtpClient.ConnectAsync(_emailSettings.SmtpHost, _emailSettings.SmtpPort, SecureSocketOptions.StartTls);

            await _smtpClient.AuthenticateAsync(_emailSettings.SmtpUser, _emailSettings.SmtpPassword);

            await _smtpClient.SendAsync(email);

            await _smtpClient.DisconnectAsync(true);
        }
コード例 #5
0
        public async Task Send(EmailMessage emailMessage, EmailConfiguration emailConfiguration)
        {
            var message = new MimeMessage();

            message.To.AddRange(emailMessage.ToAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
            message.From.AddRange(emailMessage.FromAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
            message.Subject = emailMessage.Subject;
            message.Body    = new TextPart(TextFormat.Html)
            {
                Text = emailMessage.Content
            };
            _smtpClient.ServerCertificateValidationCallback = (s, c, h, e) => true;
            await _smtpClient.ConnectAsync(emailConfiguration.SmtpServer, emailConfiguration.SmtpPort, SecureSocketOptions.Auto);

            await _smtpClient.AuthenticateAsync(emailConfiguration.SmtpUsername, emailConfiguration.SmtpPassword);

            await _smtpClient.SendAsync(message);

            await _smtpClient.DisconnectAsync(true);
        }
コード例 #6
0
        private async Task ConnectAsync(ISmtpClient client, EmailConfig.OutgoingConfig cfg,
                                        CancellationToken cancellationToken)
        {
            _log.LogDebug("Connecting to mail server using {@Config}", cfg);
            var socketOptions = client.ConfigureSecurity(cfg.UseSecureMode);
            await Policy
            .Handle <SocketException>().Or <System.IO.IOException>().Or <SslHandshakeException>()
            .WaitAndRetryAsync(_retryConfig.Max, _ => _retryConfig.Delay,
                               (exc, delay, attempt, _) => _log.LogError(exc, Message.ConnError, attempt, cfg, delay))
            .ExecuteAsync(token => client.ConnectAsync(cfg.ServerAddress, cfg.Port, socketOptions, token),
                          cancellationToken);

            if (!string.IsNullOrWhiteSpace(cfg.Username) && !string.IsNullOrWhiteSpace(cfg.Password))
            {
                await Policy.Handle <SocketException>()
                .WaitAndRetryAsync(_retryConfig.Max, _ => _retryConfig.Delay,
                                   (exc, delay, attempt, _) => _log.LogError(exc, Message.AuthError, attempt, cfg, delay))
                .ExecuteAsync(token => client.AuthenticateAsync(cfg.Username, cfg.Password, token),
                              cancellationToken);
            }
        }
コード例 #7
0
        private async Task ConnectToSmtpServer()
        {
            try
            {
                await _smtpClient.ConnectAsync(_smtpConfiguration.SmtpServer, _smtpConfiguration.SmtpPort);

                if (_smtpClient.Capabilities.HasFlag(SmtpCapabilities.Authentication))
                {
                    await _smtpClient.AuthenticateAsync(_smtpConfiguration.SenderUserName, _smtpConfiguration.SenderPassword);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to connect/authenticate to the SMTP server ({address}:{port})!",
                                 _smtpConfiguration.SmtpServer,
                                 _smtpConfiguration.SmtpPort);

                if (_smtpClient.IsConnected)
                {
                    await _smtpClient.DisconnectAsync(true);
                }
            }
        }
コード例 #8
0
        public async Task SendErrorsAsync(IEnumerable <ServiceCheckResultDto> serviceCheckResults)
        {
            Guard.Against.NullOrEmpty(serviceCheckResults, nameof(serviceCheckResults));

            try
            {
                var message = _emailBuilder.BuildUnhealthyServicesEmail(serviceCheckResults,
                                                                        _smtpConfiguration.SenderName,
                                                                        _smtpConfiguration.SenderEmail,
                                                                        _notificationConfiguration.NotificationEmails);

                await _smtpClient.ConnectAsync(_smtpConfiguration.SmtpServer, _smtpConfiguration.SmtpPort);

                await _smtpClient.AuthenticateAsync(_smtpConfiguration.SenderUserName, _smtpConfiguration.SenderPassword);

                await _smtpClient.SendAsync(message);

                await _smtpClient.DisconnectAsync(true);
            }
            catch (Exception ex)
            {
                _logger.LogError("Failed to send email about unhealthy services", ex);
            }
        }
コード例 #9
0
ファイル: EmailService.cs プロジェクト: inshapardaz/api
        public async Task SendAsync(string to, string subject, string html, string from = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // create message
            var email = new MimeMessage();

            email.From.Add(MailboxAddress.Parse(from ?? _appSettings.EmailFrom));
            email.To.Add(MailboxAddress.Parse(to));
            email.Subject = subject;
            email.Body    = new TextPart(TextFormat.Html)
            {
                Text = html
            };

            await _smtpClient.ConnectAsync(_appSettings.SmtpHost, _appSettings.SmtpPort, _appSettings.SmtpTls?SecureSocketOptions.StartTls : SecureSocketOptions.Auto, cancellationToken);

            if (!string.IsNullOrWhiteSpace(_appSettings.SmtpUser))
            {
                await _smtpClient.AuthenticateAsync(_appSettings.SmtpUser, _appSettings.SmtpPass, cancellationToken);
            }

            await _smtpClient.SendAsync(email, cancellationToken);

            await _smtpClient.DisconnectAsync(true, cancellationToken);
        }
コード例 #10
0
        private async Task ConnectSmtpClientAsync()
        {
            await _smtpClient.ConnectAsync(_settings.Smtp.Host, _settings.Smtp.Port, _settings.Smtp.UseSsl);

            await _smtpClient.AuthenticateAsync(_settings.Smtp.Username, _settings.Smtp.Password);
        }
コード例 #11
0
ファイル: Sender.cs プロジェクト: Denuin/SendMail
        public async Task <bool> Send(Dictionary <string, string> argsMap)
        {
            bool result = false;

            string[] to      = argsMap["-to"].Split(';');
            string[] from    = argsMap["-from"].Split(',');
            string   subject = argsMap["-subject"];
            string   body    = argsMap["-body"];

            string[] smtp = argsMap["-smtp"].Split(':');
            string[] user = argsMap["-user"].Split('/');

            string[] att = null;
            if (argsMap.TryGetValue("-att", out string valueAtt))
            {
                att = valueAtt.Split(';');
            }

            if (smtp?.Length != 2)
            {
                Console.WriteLine("Send Error: -smtp格式有误!");
                return(result);
            }
            if (user?.Length != 2)
            {
                Console.WriteLine("Send Error: -user格式有误!");
                return(result);
            }

            #region 发邮件

            _smtp.ConnectAsync(smtp[0], Convert.ToInt32(smtp[1]), SecureSocketOptions.StartTls).Wait();
            _smtp.AuthenticateAsync(user[0], user[1]).Wait();

            _smtp.MessageSent += (sender, args) =>
            {
                Console.WriteLine($"Send Message: {args.Response}");
            };

            var message = new MimeMessage();
            InternetAddressList list = new InternetAddressList();
            foreach (var p in to)
            {
                list.Add(new MailboxAddress(p, p));
            }
            message.To.AddRange(list);
            if (from.Length > 1)
            {
                message.From.Add(new MailboxAddress(from[0], from[1]));
            }
            else
            {
                message.From.Add(new MailboxAddress(from[0], from[0]));
            }
            message.Subject = subject;

            var builder = new BodyBuilder();
            if (att != null)
            {
                foreach (var p in att)
                {
                    if (File.Exists(p))
                    {
                        builder.Attachments.Add(p);
                    }
                    else
                    {
                        Console.WriteLine($"提示: 附件文件 {p} 不存在。");
                    }
                }
            }
            builder.TextBody = body;
            message.Body     = builder.ToMessageBody();
            await _smtp.SendAsync(message);

            #endregion 发邮件

            return(result);
        }
コード例 #12
0
        private async Task ConnectToSmtpAsync(string host, int port, string from, string password, CancellationToken cancellationToken)
        {
            await _smtpClient.ConnectAsync(host, port, false, cancellationToken);

            await _smtpClient.AuthenticateAsync(from, password, cancellationToken);
        }