Example #1
0
        protected override BaseProtocolClient Connect()
        {
            try
            {
                var pop = MailClientBuilder.Pop();
                pop.Authenticated += OnAuthenticated;

                log.Debug("Connecting to {0}", Account.EMail);

                pop.Authorize(new MailServerSettings
                {
                    AccountName        = Account.Account,
                    AccountPass        = Account.Password,
                    AuthenticationType = Account.AuthenticationTypeIn,
                    EncryptionType     = Account.IncomingEncryptionType,
                    Port = Account.Port,
                    Url  = Account.Server
                }, Account.AuthorizeTimeoutInMilliseconds, log);

                pop.LoadOriginalData = LoadOriginalEmlData;

                return(pop);
            }
            catch (Exception)
            {
                if (!Account.AuthErrorDate.HasValue)
                {
                    mailBoxManager.SetMailboxAuthError(Account, true);
                }

                throw;
            }
            finally
            {
                mailBoxManager.SetEmailLoginDelayExpires(Account.EMail.ToString(), Account.ServerLoginDelay);
            }
        }
Example #2
0
        private static void Main(string[] args)
        {
            XmlConfigurator.Configure();

            _logger = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Log4Net, "EMLDownloader");

            var options = new Options();

            if (CommandLine.Parser.Default.ParseArgumentsStrict(args, options,
                                                                () => _logger.Info("Bad command line parameters.")))
            {
                Imap4Client imap = null;
                Pop3Client  pop  = null;

                try
                {
                    _logger.Info("Searching account with id {0}", options.MailboxId);

                    var mailbox = GetMailBox(options.MailboxId);

                    if (mailbox == null)
                    {
                        _logger.Info("Account not found.");
                        ShowAnyKey();
                        return;
                    }

                    string messageEml;

                    if (mailbox.Imap)
                    {
                        _logger.Info("ConnectionType is IMAP4");

                        imap = MailClientBuilder.Imap();

                        imap.AuthenticateImap(mailbox, _logger);

                        _logger.Info(imap.ServerCapabilities);

                        var mailboxesString = imap.GetImapMailboxes();

                        _logger.Info(mailboxesString);

                        if (string.IsNullOrEmpty(options.MessageUid))
                        {
                            _logger.Info("MessageUid not setup.");
                            ShowAnyKey();
                            return;
                        }

                        var uidlStucture = ParserImapUidl(options.MessageUid);

                        if (uidlStucture.folderId != 1)
                        {
                            throw new FormatException("Only inbox messages are supported for downloading.");
                        }

                        var mb = imap.SelectMailbox("INBOX");

                        var uidList = mb.UidSearch("UID 1:*");

                        if (!uidList.Any(uid => uid == uidlStucture.uid))
                        {
                            throw new FileNotFoundException(string.Format("Message with uid {0} not found in inbox",
                                                                          uidlStucture.uid));
                        }

                        _logger.Info("Try Fetch.UidMessageStringPeek");

                        messageEml = mb.Fetch.UidMessageStringPeek(uidlStucture.uid);
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(options.MessageUid))
                        {
                            _logger.Info("MessageUid not setup.");
                            ShowAnyKey();
                            return;
                        }

                        _logger.Info("ConnectionType is POP3");

                        pop = MailClientBuilder.Pop();

                        pop.Authorize(new MailServerSettings
                        {
                            AccountName        = mailbox.Account,
                            AccountPass        = mailbox.Password,
                            AuthenticationType = mailbox.AuthenticationTypeIn,
                            EncryptionType     = mailbox.IncomingEncryptionType,
                            Port = mailbox.Port,
                            Url  = mailbox.Server
                        }, mailbox.AuthorizeTimeoutInMilliseconds, _logger);

                        _logger.Debug("UpdateStats()");

                        pop.UpdateStats();

                        var index = pop.GetMessageIndex(options.MessageUid);

                        if (index < 1)
                        {
                            throw new FileNotFoundException(string.Format("Message with uid {0} not found in inbox",
                                                                          options.MessageUid));
                        }

                        messageEml = pop.RetrieveMessageString(index);
                    }

                    _logger.Info("Try StoreToFile");
                    var now  = DateTime.Now;
                    var path = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Downloads"),
                                            string.Format("uid_{0}_{1}.eml", options.MessageUid,
                                                          now.ToString("dd_MM_yyyy_hh_mm")));
                    var pathFile = StoreToFile(messageEml, path, true);

                    _logger.Info("[SUCCESS] File was stored into path \"{0}\"", pathFile);
                }
                catch (Exception ex)
                {
                    _logger.Info(ex.ToString());
                }
                finally
                {
                    if (imap != null && imap.IsConnected)
                    {
                        imap.Disconnect();
                    }
                    else if (pop != null && pop.IsConnected)
                    {
                        pop.Disconnect();
                    }
                }
            }

            ShowAnyKey();
        }
Example #3
0
        private bool RetrievePop(int max_messages_per_session, WaitHandle stop_event, out int processed_messages_count)
        {
            var pop = MailClientBuilder.Pop();

            try
            {
                pop.Authenticated += OnAuthenticated;

                _log.Debug("Connecting to {0}", Account.EMail);

                try
                {
                    pop.Authorize(new MailServerSettings
                    {
                        AccountName        = Account.Account,
                        AccountPass        = Account.Password,
                        AuthenticationType = Account.AuthenticationTypeIn,
                        EncryptionType     = Account.IncomingEncryptionType,
                        Port = Account.Port,
                        Url  = Account.Server
                    }, Account.AuthorizeTimeoutInMilliseconds, _log);
                }
                catch (TargetInvocationException ex_target)
                {
                    throw ex_target.InnerException;
                }

                UpdateTimeCheckedIfNeeded();

                _log.Debug("UpdateStats()");

                pop.UpdateStats();

                _log.Debug("GetCAPA()");

                GetCAPA(pop);

                _log.Info("Account: MessagesCount={0}, TotalSize={1}, UIDL={2}, LoginDelay={3}",
                          pop.MessageCount, pop.TotalSize, IsUidlSupported, Account.ServerLoginDelay);

                if (ProcessMessagesPop(pop, max_messages_per_session, stop_event, out processed_messages_count))
                { // If all messages are proccessed
                    Account.MessagesCount = pop.MessageCount;
                    Account.Size          = pop.TotalSize;
                    _log.Info("Account '{0}' has been processed.", Account.EMail);
                }

                LastRetrieve = DateTime.UtcNow;

                return(true);
            }
            catch (SocketException s_ex)
            {
                if (s_ex.SocketErrorCode == SocketError.HostNotFound)
                {
                    if (OnAuthFailed != null)
                    {
                        OnAuthFailed(Account, "Host unknown");
                    }
                }

                _log.Warn("Retrieve() Pop3: {0} Port: {1} Account: '{2}' ErrorMessage:\r\n{3}\r\n",
                          Account.Server, Account.Port, Account.Account, s_ex.Message);

                throw;
            }
            catch (Pop3Exception e)
            {
                if (e.Command.StartsWith("USER") || e.Command.StartsWith("PASS"))
                {
                    if (OnAuthFailed != null)
                    {
                        OnAuthFailed(Account, e.Response);
                    }

                    _log.Warn("Retrieve() Pop3: {0} Port: {1} Account: '{2}' ErrorMessage:\r\n{3}\r\n",
                              Account.Server, Account.Port, Account.Account, e.Message);
                }
                else
                {
                    _log.Error("Retrieve() Pop3: {0} Port: {1} Account: '{2}' ErrorMessage:\r\n{3}\r\n",
                               Account.Server, Account.Port, Account.Account, e.ToString());
                }

                throw;
            }
            finally
            {
                try
                {
                    if (pop.IsConnected)
                    {
                        pop.Disconnect();
                    }
                }
                catch (Exception ex)
                {
                    _log.Warn("Retrieve() Pop3->Disconnect: {0} Port: {1} Account: '{2}' ErrorMessage:\r\n{3}\r\n",
                              Account.Server, Account.Port, Account.Account, ex.Message);
                }
            }
        }
        private bool RetrievePop(int max_messages_per_session, WaitHandle stop_event, out int processed_messages_count)
        {
            var pop = MailClientBuilder.Pop();

            try
            {
                pop.Authenticated += OnAuthenticated;

                _log.Debug("Connecting to {0}", Account.EMail);

                switch (Account.IncomingEncryptionType)
                {
                case EncryptionType.StartTLS:
                    pop.ConnectTLS(Account.Server, Account.Port);
                    break;

                case EncryptionType.SSL:
                    pop.ConnectSsl(Account.Server, Account.Port);
                    break;

                case EncryptionType.None:
                    pop.Connect(Account.Server, Account.Port);
                    break;
                }

                if (Account.AuthenticationTypeIn == SaslMechanism.Login)
                {
                    pop.Login(Account.Account, Account.Password, Account.Server);
                }
                else
                {
                    pop.Authenticate(Account.Account, Account.Password, Account.AuthenticationTypeIn);
                }
                UpdateTimeCheckedIfNeeded();

                _log.Debug("UpdateStats()");

                pop.UpdateStats();

                _log.Debug("GetCAPA()");

                GetCAPA(pop);

                _log.Info("Account: MessagesCount={0}, TotalSize={1}, UIDL={2}, LoginDelay={3}",
                          pop.MessageCount, pop.TotalSize, IsUidlSupported, Account.ServerLoginDelay);

                if (ProcessMessagesPop(pop, max_messages_per_session, stop_event, out processed_messages_count))
                { // If all messages are proccessed
                    Account.MessagesCount = pop.MessageCount;
                    Account.Size          = pop.TotalSize;
                    _log.Info("Account '{0}' has been processed.", Account.EMail);
                }

                LastRetrieve = DateTime.UtcNow;

                return(true);
            }
            catch (Pop3Exception e)
            {
                if (e.Command.StartsWith("USER") || e.Command.StartsWith("PASS"))
                {
                    if (OnAuthFailed != null)
                    {
                        OnAuthFailed(Account, e.Response);
                    }

                    _log.Warn("Retrieve() Pop3: {0} Port: {1} Account: '{2}' ErrorMessage:\r\n{3}\r\n",
                              Account.Server, Account.Port, Account.Account, e.Message);
                }
                else
                {
                    _log.Error("Retrieve() Pop3: {0} Port: {1} Account: '{2}' ErrorMessage:\r\n{3}\r\n",
                               Account.Server, Account.Port, Account.Account, e.ToString());
                }

                throw;
            }
            finally
            {
                try
                {
                    if (pop.IsConnected)
                    {
                        pop.Disconnect();
                    }
                }
                catch { }
            }
        }