private MailClient CreateMailClient(MailBoxData mailbox, ILog log, CancellationToken cancelToken) { MailClient client = null; var connectError = false; var stopClient = false; Stopwatch watch = null; if (_tasksConfig.CollectStatistics) { watch = new Stopwatch(); watch.Start(); } try { client = new MailClient(mailbox, cancelToken, _tasksConfig.TcpTimeout, mailbox.IsTeamlab || _tasksConfig.SslCertificateErrorsPermit, _tasksConfig.ProtocolLogPath, log, true); log.DebugFormat("MailClient.LoginImapPop(Tenant = {0}, MailboxId = {1} Address = '{2}')", mailbox.TenantId, mailbox.MailBoxId, mailbox.EMail); if (!mailbox.Imap) { client.FuncGetPop3NewMessagesIDs = uidls => MessageEngine.GetPop3NewMessagesIDs(mailbox, uidls, _tasksConfig.ChunkOfPop3Uidl); } client.Authenticated += ClientOnAuthenticated; client.LoginImapPop(); } catch (System.TimeoutException exTimeout) { log.WarnFormat( "[TIMEOUT] CreateTasks->client.LoginImapPop(Tenant = {0}, MailboxId = {1}, Address = '{2}') Exception: {3}", mailbox.TenantId, mailbox.MailBoxId, mailbox.EMail, exTimeout.ToString()); connectError = true; stopClient = true; } catch (OperationCanceledException) { log.InfoFormat( "[CANCEL] CreateTasks->client.LoginImapPop(Tenant = {0}, MailboxId = {1}, Address = '{2}')", mailbox.TenantId, mailbox.MailBoxId, mailbox.EMail); stopClient = true; } catch (AuthenticationException authEx) { log.ErrorFormat( "CreateTasks->client.LoginImapPop(Tenant = {0}, MailboxId = {1}, Address = '{2}')\r\nException: {3}\r\n", mailbox.TenantId, mailbox.MailBoxId, mailbox.EMail, authEx.ToString()); connectError = true; stopClient = true; } catch (WebException webEx) { log.ErrorFormat( "CreateTasks->client.LoginImapPop(Tenant = {0}, MailboxId = {1}, Address = '{2}')\r\nException: {3}\r\n", mailbox.TenantId, mailbox.MailBoxId, mailbox.EMail, webEx.ToString()); connectError = true; stopClient = true; } catch (Exception ex) { log.ErrorFormat( "CreateTasks->client.LoginImapPop(Tenant = {0}, MailboxId = {1}, Address = '{2}')\r\nException: {3}\r\n", mailbox.TenantId, mailbox.MailBoxId, mailbox.EMail, ex is ImapProtocolException || ex is Pop3ProtocolException ? ex.Message : ex.ToString()); stopClient = true; } finally { if (connectError) { SetMailboxAuthError(mailbox, log); } if (stopClient) { CloseMailClient(client, mailbox, log); } if (_tasksConfig.CollectStatistics && watch != null) { watch.Stop(); LogStat(CONNECT_MAILBOX, mailbox, watch.Elapsed, connectError); } } return(client); }