public HealthStatusController(IMailClient mailClient, IMessageQueueClient messageQueueClient, IElasticsearchRepository repository) : this() { MailClient = mailClient; MessageQueueClient = messageQueueClient; Repository = repository; }
public static void SendMailWithAttachment(string json, IMailClient mailClient) { var watchlist = JsonConvert.DeserializeObject<Watchlist.Watchlist>(json); var requestForm = new FormGenerator().GenerateForm(watchlist.FirstFlight); var mailSender = new MailSender(); mailSender.SendMail(json, mailClient, requestForm); }
public void Process(IMailClient mailClient, IOpticalCharacterRecognizer ocr, IClaimScanner claimScanner, IClaimManagementSystem claimManagement) { var emails = mailClient.ReadMessages(); foreach (var emailMessage in emails) { var recognizedAttachmentsContents = new List<string>(); foreach (var attachment in emailMessage.Attachments) { try { recognizedAttachmentsContents.Add(ocr.Scan(attachment.Path)); } catch (Exception e) { ProcessFailedAttachment(attachment, e); } } var claims = new List<Claim>(); foreach (var recognizedAttachmentsContent in recognizedAttachmentsContents) { try { var scanResult = claimScanner.Scan(recognizedAttachmentsContent); if (scanResult.Success) claims.Add(scanResult.Claim); else throw new Exception("Unable to find claim in attachment"); } catch (Exception e) { ProcessFailedClaim(recognizedAttachmentsContent, e); } } foreach (var claim in claims) { int retryCount = 3; while (true) { try { claimManagement.Upload(claim); } catch (Exception) { retryCount--; if (retryCount < 0) throw; else Thread.Sleep(5000); } } } } }
public AuthControllerTests() { mailClient = Substitute.For<IMailClient>(); service = Substitute.For<IAccountService>(); validator = Substitute.For<IAccountValidator>(); controller = Substitute.ForPartsOf<AuthController>(validator, service, mailClient); controller.ControllerContext.HttpContext = Substitute.For<HttpContext>(); controller.TempData = Substitute.For<ITempDataDictionary>(); controller.ControllerContext.RouteData = new RouteData(); controller.Url = Substitute.For<IUrlHelper>(); accountRegister = ObjectFactory.CreateAccountRegisterView(); accountRecovery = ObjectFactory.CreateAccountRecoveryView(); accountReset = ObjectFactory.CreateAccountResetView(); accountLogin = ObjectFactory.CreateAccountLoginView(); }
public AuthControllerTests() { mailClient = Substitute.For<IMailClient>(); service = Substitute.For<IAccountService>(); validator = Substitute.For<IAccountValidator>(); controller = Substitute.ForPartsOf<AuthController>(validator, service, mailClient); accountRegister = ObjectFactory.CreateAccountRegisterView(); accountRecovery = ObjectFactory.CreateAccountRecoveryView(); accountReset = ObjectFactory.CreateAccountResetView(); accountLogin = ObjectFactory.CreateAccountLoginView(); HttpContextBase httpContext = HttpContextFactory.CreateHttpContextBase(); controller.Url = new UrlHelper(httpContext.Request.RequestContext); controller.ControllerContext = new ControllerContext(); controller.ControllerContext.HttpContext = httpContext; }
public MailMonitorPrompter(IMailClient mailClient) { _mailClient = mailClient; Receive<CheckForMail>(_ => { Task.Run(() => _mailClient.ReadMessages()) .ContinueWith(readTask => new MailArrived(readTask.Result)) .PipeTo(Self); }); Receive<MailArrived>(message => { ScheduleNextMailCheck(); foreach (var mailObserver in _mailObservers) foreach (var mail in message.Messages) mailObserver.Tell(new MailReceived(mail.Attachments)); }); Receive<StartObserving>(_ => _mailObservers.Add(Sender)); Receive<StopObserving>(_ => _mailObservers.Remove(Sender)); }
public void PlayEmailAutomation(IMailClient client, string username, string password, bool isProtocolImap, string mailbox) { string retValue = string.Empty; int countMail = 0; retValue = client.LogIn(username, password); if (string.IsNullOrEmpty(retValue)) { retValue = client.GetTotalMail(out countMail, mailbox); if (string.IsNullOrEmpty(retValue)) { if (countMail > 0) { var _messagesIndexs = GetMailIndex(client, mailbox); //: GetPopMailIndex(countMail); _messagesIndexs = (from p in _messagesIndexs orderby p descending select p).ToList(); PerformAction(client, _messagesIndexs); } else { client.LogOut(); ((IDisposable)client).Dispose(); } } } if (!string.IsNullOrEmpty(retValue)) { throw new Exception(retValue); } }
public TransactionEntityBuilder(IMailClient _mailClient, ITransactionCardDetailBuilder _cardDetailBuilder) { MailClient = _mailClient; CardDetailBuilder = _cardDetailBuilder; }
/// <inheritdoc cref="Authenticate(IMailClient, string, int, bool, string, string, Encoding)"/> public static void Authenticate(this IMailClient client, string host, string userName, string password, Encoding?encoding = null) => Authenticate(client, host, port: 0, useSsl: false, userName, password, encoding);
public MailService(IMailClient ImailClient) { mailClient = ImailClient; }
public AuthService(IMongoContext mongoContext, IAuthTokenService authTokenService, IMailClient mailClient) { this.mongoContext = mongoContext; this.authTokenService = authTokenService; this.mailClient = mailClient; }
public void Process(IMailClient mailClient, IOpticalCharacterRecognizer ocr, IClaimScanner claimScanner, IClaimManagementSystem claimManagement) { var emails = mailClient.ReadMessages(); foreach (var emailMessage in emails) { var recognizedAttachmentsContents = new List <string>(); foreach (var attachment in emailMessage.Attachments) { try { recognizedAttachmentsContents.Add(ocr.Scan(attachment.Path)); } catch (Exception e) { ProcessFailedAttachment(attachment, e); } } var claims = new List <Claim>(); foreach (var recognizedAttachmentsContent in recognizedAttachmentsContents) { try { var scanResult = claimScanner.Scan(recognizedAttachmentsContent); if (scanResult.Success) { claims.Add(scanResult.Claim); } else { throw new Exception("Unable to find claim in attachment"); } } catch (Exception e) { ProcessFailedClaim(recognizedAttachmentsContent, e); } } foreach (var claim in claims) { int retryCount = 3; while (true) { try { claimManagement.Upload(claim); } catch (Exception) { retryCount--; if (retryCount < 0) { throw; } else { Thread.Sleep(5000); } } } } } }
public RegisteredUsersJob(ITollDataProvider _dataProvider, IMailClient _mailClient, ISettingsProvider _settings) { DataProvider = _dataProvider; MailClient = _mailClient; Settings = _settings; }
public EmailReciever(IMailClient emailClient) { this.emailClient = emailClient; }
public Emailer() { MailClient = new MailClient(); }
private List<int> GetMailIndex(IMailClient client, string mailbox) { MailFlag flag = MailFlag.All; switch (MailStatus) { case 1: flag = MailFlag.All; break; case 2: flag = MailFlag.Seen; break; case 3: flag = MailFlag.Unseen; break; } IEnumerable<int> strMsgIds = null; string mailIndexs = client.GetAllMessagesFlag(flag, out strMsgIds, mailbox); return (strMsgIds.ToList()); }
private void PerformAction(IMailClient client, IEnumerable<int> mailIndexes) { int cnt = 0; foreach (var mailIndex in mailIndexes) { ListViewItem item = null; var parser = client.FetchMailFromHeader(mailIndex); item = new ListViewItem(parser.From.ToString()); item.SubItems.Add(parser.Subject); item.SubItems.Add(parser.Headers["Date"]); item.Tag = client; //System.Threading.Thread.Sleep(50); if (this.action != null) this.action(this, new ActionEventArgs() { Item = item }); //UpdateProgressBar(pBar, mailIndexes.Count(), ++cnt); if (this._progressValueChangedEventHandler != null) this._progressValueChangedEventHandler(this, new ProgressValueChangeEventArgs() { MinValue = 0, MaxValue = mailIndexes.Count(), Value = cnt++ }); if (MailCount > 0 && cnt == MailCount) break; } }
public PromocodeAddedUserMailIntegrationEventHandler(IMailClient mailClient, IMailBuilder mailBuilder, ILogger <PromocodeAddedUserMailIntegrationEventHandler> logger) { _mailClient = mailClient ?? throw new System.ArgumentNullException(nameof(mailClient)); _mailBuilder = mailBuilder ?? throw new System.ArgumentNullException(nameof(mailBuilder)); _logger = logger ?? throw new System.ArgumentNullException(nameof(logger)); }
/// <summary> /// Every 30s queries mail server for new email. /// When there are new emails available it first download all mail headers and publishes them to the stream. /// Afterwards start downloading all mail content for just downloaded mail headers. /// </summary> /// <param name="cancel"></param> /// <returns></returns> private async Task RunCheckForNewMailAsyncLoop(CancellationToken cancel) { // Create mail client. IMailClient client = (new TrivialMailDllFactory()).Build(_serverType); try { // Publish Connecting state. _controllerStateStream.OnNext(ControllerState.Connecting); client.Connect(_serverEncryption, _host); // Publish LoggingIn state. _controllerStateStream.OnNext(ControllerState.LoggingIn); client.Login(_user, _password); // Publish Connected state. _controllerStateStream.OnNext(ControllerState.Connected); // Main loop while (!cancel.IsCancellationRequested) { // If disconnect or not encrypted (when should be) then reconnect. if (client.IsConnected && (_serverEncryption == MailServerEncryption.Unencrypted || client.IsEncrypted)) { // MailHeaderList contains new headers which will be published to subscribers. List <MailHeaderEntity> mailHeaderEntities = new List <MailHeaderEntity>(); using (IMailStorage <MailHeaderEntity> storage = _mailHeaderStorageFactory()) { // 1. Get from mail server all uids (emails). // ToDo: for Imap this could be improved. List <string> newUids = client.GetAllUids().ToList(); // 2. Distinct list of uids which are not yet stored in the database. // Let's reverse and start checking with the most recent email (the latest uid). newUids.Reverse(); List <string> uidList = new List <string>(); foreach (var uid in newUids) { if (!storage.Exists(x => x.Uid == uid)) { uidList.Add(uid); } else { break; } // Note: if any first exists, break the loop other emails are probably downloaded. } if (uidList.Count > 0) { // 3. Download mail headers. foreach (var uid in uidList) { // Download message header. var header = client.GetHeadersByUid(uid); // Note: MailDll documentation states that header can be null. if (header == null) { throw new ArgumentNullException(nameof(header), $"Downloaded an empty email header ({uid})."); } var email = new MailBuilder().CreateFromEml(header); var emailFrom = email?.From.FirstOrDefault(); var mailHeaderEntity = new MailHeaderEntity() { Uid = uid, Date = email?.Date ?? DateTime.MinValue, Subject = email?.Subject, MailFromEntity = new MailFromEntity() { Address = emailFrom?.Address, Name = emailFrom?.Name, LocalPart = emailFrom?.LocalPart, DomainPart = emailFrom?.DomainPart } }; mailHeaderEntities.Add(mailHeaderEntity); } // 4. Insert all new mail headers into the storage. storage.Insert(mailHeaderEntities); } } // For all new email headers publish them to the subscribers and download the content. // Note: This whole block is taken out from above using() to release storage handle asap. if (mailHeaderEntities.Count > 0) { // 5. Publish all new mail headers to the stream. mailHeaderEntities.ForEach(mailHeaderEntity => { _mailHeaderStream.OnNext(new MailHeader(mailHeaderEntity)); }); // 6. Start downloading content loop // It's not done in above foreach loop to not to keep storage open for too long // when running over slow internet connection. RunDownloadContentAsyncLoop(cancel, mailHeaderEntities.Select(x => x.Uid).ToList()); } } else { break; } // Check for new email again in 30s await Observable.Return(0).Delay(TimeSpan.FromSeconds(30), Scheduler.CurrentThread).ToTask(cancel); } } catch (Exception e) { Logger.Error(e, $"RunCheckForNewMailAsyncLoop"); } finally { client?.Close(); if (!cancel.IsCancellationRequested) { // Publish Disconnected state. _controllerStateStream.OnNext(ControllerState.Disconnected); } } }
public ConnectionNotifications(IMailClient mailClient, IExceptionDialog exceptionDialog) : base(mailClient, new ExceptionMessageBuilder(new AssemblyInfo()), exceptionDialog) { }
public SendMail(IMailClient mailClient) { _mailClient = mailClient; }
public RegistrationService(PublicContext publicContext, IHttpContextAccessor httpContextAccessor, IMailClient mailClient, IPasswordHasherService passwordHasherService) { _publicContext = publicContext; _httpContextAccessor = httpContextAccessor; _mailClient = mailClient; _passwordHasherService = passwordHasherService; _hasNumber = new Regex(@"[0-9]+", RegexOptions.Compiled | RegexOptions.IgnoreCase); _hasUpperChar = new Regex(@"[A-Z]+", RegexOptions.Compiled | RegexOptions.IgnoreCase); _hasMinimum8Chars = new Regex(@".{8,}", RegexOptions.Compiled | RegexOptions.IgnoreCase); _emailRegex = new Regex(@"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\""(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\"")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])", RegexOptions.Compiled | RegexOptions.IgnoreCase); }
public MailReader(IMailClient client, IMailFilter filter, IDateTimeWrap dateTime) { _Client = client; _Filter = filter; _DateTime = dateTime; }
/// <summary> /// Download MailContent for given uids. /// </summary> /// <param name="cancel"></param> /// <param name="uids"></param> /// <returns></returns> private async Task RunDownloadContentAsyncLoop(CancellationToken cancel, List <string> uids) { if (uids == null || uids.Count == 0) { return; } // Create mail client. IMailClient client = (new TrivialMailDllFactory()).Build(_serverType); try { await Task.Factory.StartNew(() => { client.Connect(_serverEncryption, _host); client.Login(_user, _password); // If is not connected or encrypted (if req) then will break and try to reconnect. if (client.IsConnected && (_serverEncryption == MailServerEncryption.Unencrypted || client.IsEncrypted)) { using (IMailStorage <MailContentEntity> storage = _mailContentStorageFactory()) { foreach (var uid in uids) { if (string.IsNullOrWhiteSpace(uid)) { continue; } if (cancel.IsCancellationRequested) { break; } var downloadRequired = true; MailContentEntity mailContentEntity = null; if (storage.Exists(x => x.Uid == uid)) { mailContentEntity = storage.FindOne(x => x.Uid == uid); if (mailContentEntity != null && mailContentEntity.IsComplete) { downloadRequired = false; } } if (downloadRequired) { // 1. Insert empty MailContent with only uid set to prevent other concurrent method to download same content. mailContentEntity = new MailContentEntity() { Uid = uid, IsComplete = false }; storage.Insert(new List <MailContentEntity>() { mailContentEntity }); // 2. Download complete email. var message = client.GetMessageByUid(uid); // Note: MailDll documentation states that message can be null. if (message != null) { IMail email = new MailBuilder().CreateFromEml(message); if (email != null) { // 3. Update database with downloaded email content. mailContentEntity = new MailContentEntity() { Uid = uid, Date = email?.Date == null ? DateTime.MinValue : email.Date.Value, Html = email.Html, MessageId = email.MessageID, Text = email.Text, CustomHeader = email?.Document.Root.Headers["x-spam"], IsComplete = true }; storage.Update(new List <MailContentEntity>() { mailContentEntity }); // Publish MailContent. _mailContentStream.OnNext(new MailContent(mailContentEntity)); } } } } } } }, cancel, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } catch (Exception e) { Logger.Error(e, $"RunDownloadContentAsync"); } finally { client?.Close(); } }
public async void SendMail(MailMessage message, IMailClient client, NetworkCredential network = null, bool async = true) { if (client == null) { await SendAsync(message); } else { message.From = new MailAddress(client.DisplayEmail, client.DisplayName); try { if (!string.IsNullOrEmpty(client.ReplyTo)) { message.ReplyToList.Add(client.ReplyTo); } if (!string.IsNullOrEmpty(client.CcList)) { message.CC.Add(client.CcList); } if (!string.IsNullOrEmpty(client.CcoList)) { message.Bcc.Add(client.CcoList); } } catch { } } try { //Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587 //For different server like yahoo this details changes and you can //get it from respective server. System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient(client.Host, client.Port ?? 25); //Enable SSL mailClient.EnableSsl = client.EnableSsl ?? false; mailClient.UseDefaultCredentials = false; //todo: parametrizar isso ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }; if (network == null) { network = new NetworkCredential(client.UserName, client.Password.Decypher()); } mailClient.Credentials = network; mailClient.SendCompleted += (sender, e) => { if (e.Error != null) { System.Diagnostics.Trace.TraceError(e.Error.ToString()); } }; if (async) { mailClient.SendAsync(message, null); } else { mailClient.Send(message); } } catch (SmtpException smex) { throw new MosesApplicationException("Para o envio dos e-mails, é necessária uma conexão segura. Não foi possível autenticar a conta de email utilizada para os envios:" + smex.Message, smex); } catch (Exception ex) { throw new MosesApplicationException("Não foi possível enviar o email:" + ex.Message, ex); } }
public ChangeUserEmailCommandHandler(IUserRepository repository, IMailClient mailClient, IMailTemplate <ConfirmEmailMailTemplateParameters> template) { _repository = repository; _mailClient = mailClient; _template = template; }
public bool SendMail(IMailClient mailClient) { return(mailClient.SendMail(From, To, Subject, Body)); }
public FetchNewEmails(ILogger <FetchNewEmails> log, IMailClient client, CosmosClient dbClient) { this.log = log; this.client = client; this.lazyContainer = new Lazy <Task <Container> >(() => CreateContainer(dbClient)); }
public SendNoteCreatedMail(IMailClient mailClient) { _mailClient = mailClient; }
public bool SendMail(IMailClient mailClient) { return(mailClient.SendMail(this.From, this.To, this.Subject, this.Body)); }
public MailImporter(IExpenseMessageParser[] parsers, ITransactionsService service, IMailClient mailClientFact) { this.messageParsers = parsers; this.transactionsService = service; this.mailClient = mailClientFact; }
/// <inheritdoc cref="AuthenticateAsync(IMailClient, string, int, bool, string, string, Encoding, CancellationToken)"/> public static Task AuthenticateAsync(this IMailClient client, string host, string userName, string password, Encoding?encoding = null, CancellationToken cancellationToken = default) => AuthenticateAsync(client, host, port: 0, useSsl: false, userName, password, encoding, cancellationToken);
public SampleSqlReportJob (FooMailClient fooMailClient) { MailClient = fooMailClient; }
public ETCTransactionEntityBuilder(IMailClient _mailClient) { MailClient = _mailClient; }
public int GetMail(PECMailBox box, string password) { String step = string.Empty; String recipient = string.Empty; short boxId = 0; int counter = 0; try { boxId = box != null ? box.Id : (short)0; recipient = box != null ? string.Format("{0} [{1}]", box.MailBoxName, box.IncomingServerName) : "Casella sconosciuta"; if (box == null) { throw new ApplicationException(); } FileLogger.Info(_loggerName, string.Format("Avvio ciclo di lettura per la casella {0} - {1}", boxId, recipient)); IMailClient client = null; //legge nuove mail if (box.IncomingServerProtocol == IncomingProtocol.Imap) { step = "ReceiveImap"; client = new ImapClient(CreateImapParams(box, password)); } else { step = "ReceivePop3"; client = new Pop3Client(CreatePop3Params(box, password)); } counter = client.GetMails(box.Id, box.IsProtocolBox.HasValue ? false : box.IsProtocolBox.Value, box.MailBoxName, _storeFacade.HeaderHashExists, box.Configuration.NoSubjectDefaultText); FileLogger.Info(_loggerName, string.Format("{0} - Eseguito Download di {1} mail. Casella {2} - {3}", step, counter, boxId, recipient)); FileLogger.Info(_loggerName, string.Format("Fine ciclo di lettura per la casella {0} - {1}", boxId, recipient)); // Segno sul log il numero di elementi da elaborare MailStoreFacade.Factory.PECMailboxLogFacade.IncomingMails(ref box, counter); return(counter); } catch (ServerException sEx) { FileLogger.Warn(_loggerName, string.Format("Errore in connessione casella {0}:{1} - Function: {2}", boxId, recipient, step), sEx); UpdateServerException(string.Format("Errore in connessione casella {0}:{1} - Function: {2} - Exception: {3} - Stacktrace: {4}", boxId, recipient, step, sEx.Message, _fullStacktrace(sEx))); return(counter); } catch (NHibernate.AssertionFailure af) { //Se mi trovo qui significa che è stato fatto il flush della sessione e allora esco dal modulo FileLogger.Error(_loggerName, "Errore NHibernate: esco dal modulo", af); _sendMessage(string.Format("Il modulo PEC ha rilevato l'errore grave {0} e verrà pertanto invocata la chiusura del JeepService.", af.Message)); Environment.Exit(1); } catch (Exception ex) { FileLogger.Error(_loggerName, string.Format("Errore in lettura casella {0}:{1} - Function: {2}", boxId, recipient, step), ex); _sendMessage(string.Format("Errore in lettura casella {0}:{1} - Function: {2} - Exception: {3} - Stacktrace: {4}", boxId, recipient, step, ex.Message, _fullStacktrace(ex))); return(counter); } return(counter); }
public Auth(IAccountValidator validator, IAccountService service, IMailClient mailClient) : base(validator, service) { MailClient = mailClient; }
public ExceptionNotification(IExceptionMessageBuilder exceptionMessageBuilder, IMailClient mailClient) { _exceptionMessageBuilder = exceptionMessageBuilder; _mailClient = mailClient; }
public TransactionsJob(IUnityContainer _container, ITollDataProvider _dataProvider, IMailClient _mailClient, ISettingsProvider _settings) { Container = _container; DataProvider = _dataProvider; MailClient = _mailClient; Settings = _settings; }
public RejectPracticeCase(IAppDbContext context, IMailClient mailClient, ITemplateCreator templateCreator) { _context = context; _mailClient = mailClient; _templateCreator = templateCreator; }
public HandledExceptionManager(IMailClient mailClient, IExceptionMessageBuilder exceptionMessageBuilder, IExceptionDialog exceptionDialog) { _mailClient = mailClient; _exceptionMessageBuilder = exceptionMessageBuilder; _exceptionDialog = exceptionDialog; }
public ForgotUserPasswordCommandHandler(IUserRepository repository, IMailClient mailClient, IMailTemplate <PasswordResetMailTemplateParameters> template) { _repository = repository; _mailClient = mailClient; _template = template; }
public EmailAutomation(IMailClient client, string username, string password) { this.client = client; this.username = username; this.password = password; }
public MailProcessor(ICustomerReader customerReader, IMailGenerator mailGenerator, IMailClient mailClient) { _customerReader = customerReader ?? throw new ArgumentNullException($"{GetType().Name}.Ctor - parameter {nameof(customerReader)} cannot be null."); _mailGenerator = mailGenerator ?? throw new ArgumentNullException($"{GetType().Name}.Ctor - parameter {nameof(mailGenerator)} cannot be null."); _mailClient = mailClient ?? throw new ArgumentNullException($"{GetType().Name}.Ctor - parameter {nameof(mailClient)} cannot be null."); }