public async Task NotifyAsync_ConfigHas3SmtpServersAndFirstOfThemDoesNotWork_SmtpClient1WasReceived() { // Arrange _smtpClient1.SendAsync(Arg.Any <MailMessage>()).Throws(new Exception()); // Act await _notificator.NotifyAsync(_emailMessage); // Assert await _smtpClient1.Received(1).SendAsync(Arg.Any <MailMessage>()); }
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); }
public async Task <IEnumerable <SendingResult> > SendAsync(IEnumerable <Email> emails) { Guard.Against.Null(emails, nameof(emails)); var sendingResults = new List <SendingResult>(); await ConnectToSmtpServer(); if (!_smtpClient.IsConnected) { return(sendingResults); } var mimeMessages = GenerateMimeMessages(emails); foreach (var mimeMessage in mimeMessages) { try { await _smtpClient.SendAsync(mimeMessage); HandleSuccessfullTaskCompletion(mimeMessage, sendingResults); } catch (Exception ex) { HandleFaultedTaskCompletion(ex, mimeMessage, sendingResults); } } await DisconnectFromSmtpServer(); return(sendingResults); }
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, ""); } }
public async Task SendEmailAsync(MailRequest mailRequest) { var email = new MimeMessage(); email.Sender = MailboxAddress.Parse(_mailSettings.Mail); email.To.Add(MailboxAddress.Parse(mailRequest.ToEmail)); email.Subject = mailRequest.Subject; var builder = new BodyBuilder(); if (mailRequest.Attachments != null) { byte[] fileBytes; foreach (var file in mailRequest.Attachments) { if (file.Length > 0) { using (var ms = new MemoryStream()) { file.CopyTo(ms); fileBytes = ms.ToArray(); } builder.Attachments.Add(file.FileName, fileBytes, ContentType.Parse(file.ContentType)); } } } builder.HtmlBody = mailRequest.Body; email.Body = builder.ToMessageBody(); //using var smtp = new SmtpClient(); _smtpClient.Connect(_mailSettings.Host, _mailSettings.Port, SecureSocketOptions.StartTls); _smtpClient.Authenticate(_mailSettings.Mail, _mailSettings.Password); await _smtpClient.SendAsync(email); _smtpClient.Disconnect(true); }
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); } }
/// <summary> /// Asynchronously Sends a MailMessage using smtpClient /// </summary> /// <param name="userState">The userState</param> /// <param name="smtpClient">leave null to use default System.Net.Mail.SmtpClient</param> public virtual async Task SendAsync(object userState = null, ISmtpClient smtpClient = null) { await Task.Run(() => { smtpClient = smtpClient ?? GetSmtpClient(); smtpClient.SendAsync(this, userState); }); }
public async Task SendAsync(MimeMessage message) { await ConnectSmtpClientAsync(); await _smtpClient.SendAsync(message); await _smtpClient.DisconnectAsync(true); }
/// <summary> /// Asynchronously Sends a MailMessage using smtpClient /// </summary> /// <param name="message">The mailMessage Object</param> /// <param name="smtpClient">leave null to use default System.Net.Mail.SmtpClient</param> public static void SendAsync(this MailMessage message, ISmtpClient smtpClient = null) { smtpClient = smtpClient ?? GetSmtpClient(); var userState = "userState"; using (smtpClient) { smtpClient.SendAsync(message, userState); } }
/// <summary> /// Begin password reset /// </summary> /// <param name="email"></param> /// <param name="ipaddress"></param> /// <param name="resetBaseUrl"></param> /// <returns></returns> public async Task BeginResetAsync(String email, String ipaddress, String returnUrl) { if (String.IsNullOrEmpty(returnUrl)) { _log.Warn($"No return url specified in reset by {email}"); return; } if (!_resetReturnDomains.Any(o => returnUrl.StartsWith(o))) { _log.Warn($"Invalid returnUrl {returnUrl} in password reset request. Email: {email}, Ip: {ipaddress}"); return; } try { var admin = await _context.Admins.SingleOrDefaultAsync(o => o.Email == email && o.Status == 1); if (admin != null) { var reset = new AdminReset { Validto = DateTime.UtcNow.AddDays(2), Id = CryptoMethods.GetRandomString(64), IpaddressRequest = ipaddress }; admin.AdminReset.Add(reset); await _context.SaveChangesAsync(); // todo move this to servicebus... using (var message = new System.Net.Mail.MailMessage("*****@*****.**", email)) { message.Subject = "Flexinets Portal - Password reset"; message.Bcc.Add("*****@*****.**"); message.Body = "To reset your password please follow this link" + Environment.NewLine + Environment.NewLine + returnUrl + reset.Id + Environment.NewLine + Environment.NewLine + "If you did not start the reset process, you can ignore this message."; await _smtpClient.SendAsync(message); _log.Info($"Password reset started for email {email}"); } } else { _log.Warn($"Failed password reset for {email}"); } } catch (Exception ex) { _log.Error($"Failed password reset for {email}", ex); } }
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); }
private async Task SendOrder(CancellationToken stoppingToken, Order order, MimeMessage message) { try { _logger?.LogInformation($"Sending message: {order}"); await _smtpClient.SendAsync(message, stoppingToken); } catch (ServiceNotConnectedException ex) { this._logger?.Log(LogLevel.Error, $"Sending order error {ex}."); throw; } }
public void SendMail(string to, string subject, string body) { // Create the mail message (from, to, subject, body) var mailMessage = new MailMessage { From = new MailAddress(config.EmailFrom, config.SenderDisplayName) }; mailMessage.To.Add(to); mailMessage.Subject = subject; mailMessage.Body = body; mailMessage.IsBodyHtml = true; mailMessage.Priority = MailPriority.High; // send the mail _smtpClient.SendAsync(mailMessage, ""); }
/// <summary> /// Sends batch of <see cref="QueuedEmail"/>. /// </summary> /// <param name="batch">Current batch of <see cref="QueuedEmail"/></param> /// <param name="client"><see cref="ISmtpClient"/> to use for sending mails.</param> /// <param name="saveToDisk">Specifies whether mails should be saved to disk.</param> /// <returns></returns> private async Task <bool> ProcessMailBatchAsync(IEnumerable <QueuedEmail> batch, ISmtpClient client, bool saveToDisk, CancellationToken cancelToken = default) { var result = false; foreach (var queuedEmail in batch) { if (cancelToken.IsCancellationRequested) { break; } try { using var msg = ConvertMail(queuedEmail); if (saveToDisk) { await _mailService.SaveAsync(_emailAccountSettings.PickupDirectoryLocation, msg); } else { await client.SendAsync(msg, cancelToken); if (_emailAccountSettings.MailSendingDelay > 0) { await Task.Delay(_emailAccountSettings.MailSendingDelay, cancelToken); } } queuedEmail.SentOnUtc = DateTime.UtcNow; result = true; } catch (Exception ex) { Logger.Error(ex, string.Concat(T("Admin.Common.ErrorSendingEmail"), ": ", ex.Message)); result = false; } finally { queuedEmail.SentTries += 1; } } return(result); }
public async Task NotifyAsync_AllSmtpServersDoesNotWork_ReturnFailureWithCorrectMessage() { // Arrange var error1 = "error 1"; var error2 = "error 2"; var error3 = "error 3"; _smtpClient1.SendAsync(Arg.Any <MailMessage>()).Throws(new Exception(error1)); _smtpClient2.SendAsync(Arg.Any <MailMessage>()).Throws(new Exception(error2)); _smtpClient3.SendAsync(Arg.Any <MailMessage>()).Throws(new Exception(error3)); // Act var result = await _notificator.NotifyAsync(_emailMessage); // Assert Assert.True(result.Failure); Assert.Contains($"SMTP {_smtpClient1.Host} throw an error: {error1}", result.ToString()); Assert.Contains($"SMTP {_smtpClient2.Host} throw an error: {error2}", result.ToString()); Assert.Contains($"SMTP {_smtpClient3.Host} throw an error: {error3}", result.ToString()); }
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); }
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); } }
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); }
/// <summary> /// Sends a single email. /// </summary> /// <param name="message">Message to send.</param> public static Task SendAsync(this ISmtpClient client, MailMessage message, CancellationToken cancelToken = default) { Guard.NotNull(message, nameof(message)); return(client.SendAsync(new[] { message }, cancelToken)); }
public Task NotifyAsync(Employee employee, string message) { return(_client.SendAsync(employee.Alias, message)); }
/// <summary> /// Asynchronously Sends a MailMessage using smtpClient /// </summary> /// <param name="userState">The userState</param> /// <param name="smtpClient">leave null to use default System.Net.Mail.SmtpClient</param> public virtual void SendAsync(object userState = null, ISmtpClient smtpClient = null) { smtpClient = smtpClient ?? GetSmtpClient(); smtpClient.SendAsync(this, userState); }
/// <summary> /// Asynchronously Sends a MailMessage using smtpClient /// </summary> /// <param name="message">The mailMessage Object</param> /// <param name="userState">The userState</param> /// <param name="smtpClient">leave null to use default System.Net.Mail.SmtpClient</param> public static void SendAsync(this MailMessage message, object userState = null, ISmtpClient smtpClient = null) { smtpClient = smtpClient ?? GetSmtpClient(); smtpClient.SendAsync(message, userState); }
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); }