/// <summary> /// Add new transport to transports list /// Format: /// 1) Transport type /// 2...) Transport args /// </summary> public bool AddTransport(string[] args) { ITransport transport; var transportArgs = new string[args.Length - 2]; for (int i = 2; i < args.Length; i++) { transportArgs[i - 2] = args[i]; } switch (args[1]) { case "MailTransport": transport = new MailTransport(transportArgs); break; case "HttpTransport": transport = new HttpTransport(transportArgs); break; default: return(false); } Program.TransportManager.AddTransport(transport); return(true); }
/// <summary> /// Отправка сообщения. /// </summary> /// <param name="message"> Сообщение в формате <see cref="MimeMessage" />. </param> /// <returns> Результат отправки. </returns> private async Task <SendMailResult> SendMailAsync(MimeMessage message) { if (_disposed) { throw new ObjectDisposedException(nameof(MailTransport), "Для экземпляра сервиса Email-сообщений был вызвван метод Dispose()"); } try { await MailTransport.ConnectAsync( Options.Host, Options.Port, GetSecureSocketOptions(Options.EnableSsl)); await MailTransport.AuthenticateAsync( Options.Login, Options.Password); await MailTransport.SendAsync(message); await MailTransport.DisconnectAsync(true); return(SendMailResult.CreateSuccessResult()); } catch (Exception ex) { return(SendMailResult.CreateErrorResult(ex)); } }
private async Task SendMailsAsync(IReadOnlyList <Task <Mail> > produceMailTasks, WritableDataContext dbContext, CancellationToken cancellationToken) { try { for (int i = 0, n = produceMailTasks.Count; i < n; i++) { var mail = await produceMailTasks[i].ConfigureAwait(false); if (mail.Message != null) { if (!_smtpClient.IsConnected) { try { await _smtpClient.ConnectAsync(_smtpHost, _smtpPort, _smtpSecurity, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when(!(ex is OperationCanceledException)) { var smtpClient = _smtpClient; _smtpClient = _smtpClientFactory(); smtpClient.Dispose(); throw; } if (_smtpCredentials != null) { await _smtpClient.AuthenticateAsync(_smtpCredentials, cancellationToken).ConfigureAwait(false); } } await SendMailAsync(dbContext, mail, cancellationToken).ConfigureAwait(false); } else if (mail.Error != null) { await HandleMailErrorAsync(dbContext, mail, cancellationToken).ConfigureAwait(false); } else { // we should never get here throw new InvalidOperationException(); } } } finally { if (_smtpClient.IsConnected) { await _smtpClient.DisconnectAsync(quit : true, cancellationToken).ConfigureAwait(false); } } }
/// <inheritdoc /> public void Dispose() { MailTransport?.Dispose(); _disposed = true; }
public MailSenderService(IServiceScopeFactory serviceScopeFactory, IMailTypeCatalog mailTypeCatalog, IGuidProvider guidProvider, IClock clock, IOptions <SmtpOptions>?smtpOptions, IOptions <MailSenderServiceOptions>?options, ILogger <MailSenderService>?logger) { if (guidProvider == null) { throw new ArgumentNullException(nameof(guidProvider)); } _serviceScopeFactory = serviceScopeFactory ?? throw new ArgumentNullException(nameof(serviceScopeFactory)); _mailTypeCatalog = mailTypeCatalog ?? throw new ArgumentNullException(nameof(mailTypeCatalog)); _clock = clock ?? throw new ArgumentNullException(nameof(clock)); var smtpOptionsValue = smtpOptions?.Value; var usePickupDir = smtpOptionsValue?.UsePickupDir ?? true; if (usePickupDir) { var pickupDirPath = smtpOptionsValue?.PickupDirPath ?? string.Empty; if (!Path.IsPathRooted(pickupDirPath)) { pickupDirPath = Path.Combine(AppContext.BaseDirectory, pickupDirPath); } _smtpClientFactory = () => new PickupDirMailClient(guidProvider, pickupDirPath); } else { _smtpHost = smtpOptionsValue !.Host ?? throw new ArgumentException($"{nameof(SmtpOptions.Host)} must be specified.", nameof(smtpOptions)); _smtpPort = smtpOptionsValue.Port ?? SmtpOptions.DefaultPort; _smtpSecurity = smtpOptionsValue.Security ?? SmtpOptions.DefaultSecurity; var smtpUserName = smtpOptionsValue.UserName; var smtpPassword = smtpOptionsValue.Password; _smtpCredentials = smtpUserName != null || smtpPassword != null ? new NetworkCredential(smtpUserName, smtpPassword) : null; var smtpTimeout = smtpOptionsValue.Timeout ?? SmtpOptions.DefaultTimeout; _smtpClientFactory = () => new SmtpClient { Timeout = checked ((int)smtpTimeout.TotalMilliseconds) }; } _smtpClient = _smtpClientFactory(); var optionsValue = options?.Value; _batchSize = optionsValue?.BatchSize ?? MailSenderServiceOptions.DefaultBatchSize; _maxSleepTime = optionsValue?.MaxSleepTime ?? MailSenderServiceOptions.DefaultMaxSleepTime; _initialSendRetryTime = optionsValue?.InitialSendRetryTime ?? _maxSleepTime; if (_initialSendRetryTime <= TimeSpan.Zero) { _initialSendRetryTime = MailSenderServiceOptions.DefaultInitialSendRetryTime; } _maxSendRetryTime = optionsValue?.MaxSendRetryTime ?? MailSenderServiceOptions.DefaultMaxSendRetryTime; if (_maxSendRetryTime < _initialSendRetryTime) { _maxSendRetryTime = _initialSendRetryTime; } _delayOnUnexpectedError = optionsValue?.DelayOnUnexpectedError ?? MailSenderServiceOptions.DefaultDelayOnUnexpectedError; _logger = logger ?? (ILogger)NullLogger.Instance; }
private void SendOnJestAdminInfo(LectioDivinaWeek lectioWeek) { OnNotification("Wysyłam mail do admina OnJest"); var mailer = new MailTransport(); mailer.SendMail("Lectio Divina " + Localization.Date2PlStr(lectioWeek.Title.SundayDate), "wysłane", Properties.Settings.Default.OnJestAdminEmail, "OnJest Admin"); }
public MailHelper(MailTransport mailer, IRegistryReader registryReader, IConfiguration configuration) { _configuration = configuration; this.mailer = mailer; this.registryReader = registryReader; }
private void ReceiveLectiosFromServer() { int count = 0; System.Threading.Tasks.Task.Factory .StartNew(() => { Log("Odbieram z serwera Lectio od autorów"); MailTransport transport = new MailTransport(); transport.Notification += Progress_Notification; List<OneDayContemplation> contemplations = transport.RetrieveContemplations(); foreach (var contemplation in contemplations) { AddContemplationToWeek(contemplation); count++; } }) .ContinueWith((t) => { if (t.Exception != null) { string msg = "Nie uda³o siê odebraæ Lectio:\r\n" + t.Exception.InnerException.Message; Log(msg); dialogService.ShowError(msg, "B³¹d", "OK", null); } else { Log(String.Format("Odebrano {0} rozwa¿añ", count)); dialogService.ShowMessage(String.Format("Zakoñczono odbieranie Lectio, odebrano {0}. ", count), "Informacja"); } } ); }
private void SendAndHandleErrors() { try { dialogService.SetBusy(); LectioDivina.Service.MailTransport transport = new MailTransport(); transport.SendToPublisher(contemplation); dialogService.ShowMessage("Wysy³anie zakoñczone", "Informacja"); } catch (Exception ex) { dialogService.ShowError("Nie uda³o siê wys³aæ rozwa¿ania.\r\n" + GetNestedExceptionMessage(ex) + "\r\nSpróbuj ponownie i jeœli problem siê powtarza, skontaktuj siê z T.R.", "Problem", "Ok", () => { }); } finally { dialogService.SetNormal(); } }