Exemplo n.º 1
0
        protected override BaseProtocolClient Connect()
        {
            try
            {
                var imap = MailClientBuilder.Imap();
                imap.Authenticated += OnAuthenticated;
                imap.AuthenticateImap(Account, log);
                imap.LoadOriginalData = LoadOriginalEmlData;

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

                throw;
            }
            finally
            {
                mailBoxManager.SetEmailLoginDelayExpires(Account.EMail.ToString(), Account.ServerLoginDelay);
            }
        }
Exemplo n.º 2
0
        private void StoreMessageToImapSentFolder(MailBox mbox, Message mime_message)
        {
            if (mime_message == null || !mbox.Imap)
            {
                return;
            }

            var imap = MailClientBuilder.Imap();

            try
            {
                imap.AuthenticateImap(mbox, log);

                // reverse folders and order them to download tagged incoming messages first
                // gmail returns tagged letters in mailboxes & duplicate them in inbox
                // to retrieve tags - first we need to download files from "sub" mailboxes
                var sent_folder =
                    imap.GetImapMailboxes(mbox.Server, MailQueueItemSettings.SpecialDomainFolders,
                                          MailQueueItemSettings.SkipImapFlags, MailQueueItemSettings.ImapFlags)
                    .FirstOrDefault(m => m.folder_id == MailFolder.Ids.sent);

                if (sent_folder == null)
                {
                    throw new InvalidDataException(String.Format("Cannot find Sent folder over Imap. MailboxId={0}",
                                                                 mbox.MailBoxId));
                }

                var mb_obj = imap.SelectMailbox(sent_folder.name);

                var flags = new FlagCollection {
                    "Seen"
                };

                var response = mb_obj.Append(mime_message, flags);

                log.Info("StoreMessageToImapSentFolder() in MailboxId={0} successed! Returned: '{0}'", response);
            }
            catch (Exception ex)
            {
                log.Error("StoreMessageToSentFolder() in MailboxId={0} failed with exception:\r\n{1}",
                          mbox.MailBoxId, ex.ToString());
            }
            finally
            {
                try
                {
                    if (imap.IsConnected)
                    {
                        imap.Disconnect();
                    }
                }
                catch
                {
                }
            }
        }
Exemplo n.º 3
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);
            }
        }
Exemplo n.º 4
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);
                }
            }
        }
Exemplo n.º 5
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();
        }
Exemplo n.º 6
0
        public int Send(int tenant, string username, MailSendItem originalMessage, int mailId, int mailboxId)
        {
            var mbox = manager.GetUnremovedMailBox(mailboxId);

            if (mbox == null)
            {
                throw new ArgumentException("no such mailbox");
            }

            originalMessage.MailboxId = mbox.MailBoxId;

            if (mbox.Name != "")
            {
                originalMessage.DisplayName = mbox.Name;
            }

            if (string.IsNullOrEmpty(originalMessage.HtmlBody))
            {
                originalMessage.HtmlBody = EMPTY_HTML_BODY;
            }

            var messageItem = SaveToDraft(originalMessage, mailId, mbox);

            if (messageItem.Id > 0)
            {
                var userCulture   = Thread.CurrentThread.CurrentCulture;
                var userUiCulture = Thread.CurrentThread.CurrentUICulture;
                var scheme        = HttpContext.Current.Request.GetUrlRewriter().Scheme;
                // move to_addresses temp
                manager.SetConversationsFolder(tenant, username, MailFolder.Ids.temp,
                                               new List <int> {
                    (Int32)messageItem.Id
                });
                manager.SetMessageFolderRestore(tenant, username, MailFolder.Ids.drafts,
                                                (int)messageItem.Id);
                ThreadPool.QueueUserWorkItem(delegate
                {
                    Message mimeMessage;
                    try
                    {
                        Thread.CurrentThread.CurrentCulture   = userCulture;
                        Thread.CurrentThread.CurrentUICulture = userUiCulture;

                        CoreContext.TenantManager.SetCurrentTenant(tenant);
                        SecurityContext.AuthenticateMe(new Guid(username));

                        ApiHelper.SetupScheme(scheme);

                        originalMessage.ChangeEmbededAttachmentLinks(tenant, username);
                        originalMessage.ChangeSmileLinks();

                        originalMessage.ChangeAttachedFileLinksAddresses(tenant);
                        originalMessage.ChangeAttachedFileLinksImages();

                        mimeMessage = originalMessage.ToMimeMessage(tenant, username, true);

                        var smptClient = MailClientBuilder.Smtp();

                        if (mbox.RefreshToken != null)
                        {
                            smptClient.SendSsl(mimeMessage, mbox.SmtpServer, mbox.SmtpPort,
                                               mbox.SmtpAccount, GetAccessToken(mbox),
                                               SaslMechanism.OAuth2);
                        }
                        else if (mbox.OutcomingEncryptionType == EncryptionType.None)
                        {
                            if (mbox.AuthenticationTypeSmtp == SaslMechanism.None)
                            {
                                smptClient.Send(mimeMessage, mbox.SmtpServer, mbox.SmtpPort);
                            }
                            else
                            {
                                smptClient.Send(mimeMessage, mbox.SmtpServer, mbox.SmtpPort,
                                                mbox.SmtpAccount, mbox.SmtpPassword,
                                                mbox.AuthenticationTypeSmtp);
                            }
                        }
                        else
                        {
                            if (mbox.AuthenticationTypeSmtp == SaslMechanism.None)
                            {
                                smptClient.SendSsl(mimeMessage, mbox.SmtpServer, mbox.SmtpPort,
                                                   mbox.OutcomingEncryptionType);
                            }
                            else
                            {
                                smptClient.SendSsl(mimeMessage, mbox.SmtpServer, mbox.SmtpPort,
                                                   mbox.SmtpAccount, mbox.SmtpPassword,
                                                   mbox.AuthenticationTypeSmtp,
                                                   mbox.OutcomingEncryptionType);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        AddNotificationAlertToMailbox(originalMessage, (Int32)messageItem.Id, ex, mbox);

                        // move to_addresses drafts
                        manager.SetConversationsFolder(tenant, username, MailFolder.Ids.drafts,
                                                       new List <int> {
                            (Int32)messageItem.Id
                        });
                        manager.SetMessageFolderRestore(tenant, username, MailFolder.Ids.drafts,
                                                        (int)messageItem.Id);

                        // send unsuccess notification
                        SendMailNotification(tenant, username, 1);

                        return;
                    }

                    SendMailNotification(tenant, username, 0);

                    try
                    {
                        // message was correctly send - lets update its chains id
                        var draftChainId = messageItem.ChainId;
                        // before moving message from draft to sent folder - lets recalculate its correct chain id
                        messageItem.ChainId = manager.DetectChainId(mbox, messageItem);
                        // push new message correct chain id to db
                        manager.UpdateMessageChainId(mbox, messageItem.Id, MailFolder.Ids.temp, draftChainId,
                                                     messageItem.ChainId);

                        manager.UpdateCrmLinkedChainId(mbox.MailBoxId, tenant, draftChainId,
                                                       messageItem.ChainId);

                        // move to_addresses sent
                        manager.SetConversationsFolder(tenant, username, MailFolder.Ids.sent,
                                                       new List <int> {
                            (Int32)messageItem.Id
                        });
                        manager.SetMessageFolderRestore(tenant, username, MailFolder.Ids.sent,
                                                        (int)messageItem.Id);

                        manager.AddRelationshipEventForLinkedAccounts(mbox, messageItem, log);

                        manager.SaveEmailInData(mbox, messageItem, log);

                        manager.SaveMailContacts(mbox.TenantId, mbox.UserId, mimeMessage);

                        StoreMessageToImapSentFolder(mbox, mimeMessage);
                    }
                    catch (Exception ex)
                    {
                        log.Error("Unexpected Error in Send(), message_item.Id = {0}, {1}, {2}",
                                  messageItem.Id, ex.ToString(), ex.StackTrace);
                    }
                });
            }
            else
            {
                throw new ArgumentException("Failed to_addresses save draft");
            }

            return(messageItem.Id > 0 ? (Int32)messageItem.Id : 1); // Callback in api will be raised if value > 0
        }
        private bool RetrieveImap(int max_messages_per_session, WaitHandle stop_event, out int proccessed_messages_count)
        {
            proccessed_messages_count = max_messages_per_session;
            var imap = MailClientBuilder.Imap();

            try
            {
                imap.Authenticated += OnAuthenticated;

                try
                {
                    imap.AuthenticateImap(Account, _log);
                }
                catch (TargetInvocationException ex_target)
                {
                    throw ex_target.InnerException;
                }

                UpdateTimeCheckedIfNeeded();

                // reverse folders and order them to download tagged incoming messages first
                // gmail returns tagged letters in mailboxes & duplicate them in inbox
                // to retrieve tags - first we need to download files from "sub" mailboxes
                var mailboxes =
                    imap.GetImapMailboxes(Account.Server, MailQueueItemSettings.SpecialDomainFolders,
                                          MailQueueItemSettings.SkipImapFlags, MailQueueItemSettings.ImapFlags)
                    .Reverse()
                    .OrderBy(m => m.folder_id);

                if (!mailboxes.Any())
                {
                    _log.Error("There was no folder parsed! MailboxId={0}", Account.MailBoxId);
                }

                foreach (var mailbox in mailboxes)
                {
                    _log.Info("Select imap folder: {0}", mailbox.name);

                    Mailbox mb_obj;

                    try
                    {
                        mb_obj = imap.SelectMailbox(mailbox.name);
                    }
                    catch (Exception ex)
                    {
                        _log.Error("imap.SelectMailbox(\"{0}\") in MailboxId={1} failed with exception:\r\n{2}",
                                   mailbox.name, Account.MailBoxId, ex.ToString());
                        continue;
                    }

                    int last_folder_uid;
                    Account.ImapFolders.TryGetValue(mailbox.name, out last_folder_uid);

                    max_messages_per_session = ProcessMessages(mb_obj,
                                                               mailbox.folder_id,
                                                               last_folder_uid,
                                                               max_messages_per_session,
                                                               stop_event,
                                                               mailbox.tags);

                    if (0 == max_messages_per_session)
                    {
                        break;
                    }
                    UpdateTimeCheckedIfNeeded();
                }

                _log.Info("Account '{0}' has been processed.", Account.EMail);

                LastRetrieve = DateTime.UtcNow;

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

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

                throw;
            }
            catch (Imap4Exception e)
            {
                if (e.Message.StartsWith("Command \"LOGIN") || e.Message.StartsWith("PASS"))
                {
                    if (OnAuthFailed != null)
                    {
                        OnAuthFailed(Account, "Password changed");
                    }

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

                throw;
            }
            catch (DotNetOpenAuth.Messaging.ProtocolException ex_oauth)
            {
                if (OnAuthFailed != null)
                {
                    OnAuthFailed(Account, "Access denied");
                }

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

                throw;
            }
            finally
            {
                try
                {
                    if (imap.IsConnected)
                    {
                        imap.Disconnect();
                    }
                }
                catch (Exception ex)
                {
                    _log.Warn("RetrieveImap() Imap4->Disconnect: {0} Port: {1} Account: '{2}' ErrorMessage:\r\n{3}\r\n",
                              Account.Server, Account.Port, Account.Account, ex.Message);
                }
            }
        }
Exemplo n.º 8
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);

                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 { }
            }
        }
        private bool RetrieveImap(int max_messages_per_session, WaitHandle stop_event, out int proccessed_messages_count)
        {
            proccessed_messages_count = max_messages_per_session;
            var imap = MailClientBuilder.Imap();

            try
            {
                imap.Authenticated += OnAuthenticated;

                AuthenticateImap(imap);
                UpdateTimeCheckedIfNeeded();

                // reverse folders and order them to download tagged incoming messages first
                // gmail returns tagged letters in mailboxes & duplicate them in inbox
                // to retrieve tags - first we need to download files from "sub" mailboxes
                var mailboxes = GetImapMailboxes(imap, Account.Server).Reverse().OrderBy(m => m.folder_id);

                foreach (var mailbox in mailboxes)
                {
                    _log.Info("Select imap folder: {0}", mailbox.name);

                    var mb_obj = imap.SelectMailbox(mailbox.name);

                    int last_folder_uid;
                    Account.ImapFolders.TryGetValue(mailbox.name, out last_folder_uid);

                    max_messages_per_session = ProcessMessages(mb_obj,
                                                               mailbox.folder_id,
                                                               last_folder_uid,
                                                               max_messages_per_session,
                                                               stop_event,
                                                               mailbox.tags);

                    if (0 == max_messages_per_session)
                    {
                        break;
                    }
                    UpdateTimeCheckedIfNeeded();
                }

                _log.Info("Account '{0}' has been processed.", Account.EMail);

                LastRetrieve = DateTime.UtcNow;

                proccessed_messages_count -= max_messages_per_session;
                return(true);
            }
            catch (Imap4Exception e)
            {
                if (e.Message.StartsWith("Command \"LOGIN") || e.Message.StartsWith("PASS"))
                {
                    if (OnAuthFailed != null)
                    {
                        OnAuthFailed(Account, "Password changed");
                    }

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

                throw;
            }
            catch (DotNetOpenAuth.Messaging.ProtocolException ex_oauth)
            {
                if (OnAuthFailed != null)
                {
                    OnAuthFailed(Account, "Access denied");
                }

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

                throw;
            }
            finally
            {
                try
                {
                    if (imap.IsConnected)
                    {
                        imap.Disconnect();
                    }
                }
                catch { }
            }
        }
Exemplo n.º 10
0
        public int Send(MailDraft draft)
        {
            if (string.IsNullOrEmpty(draft.HtmlBody))
            {
                draft.HtmlBody = EMPTY_HTML_BODY;
            }

            var message = Save(draft);

            if (message.Id > 0)
            {
                ValidateAddresses(DraftFieldTypes.From, new[] { draft.From }, true);
                ValidateAddresses(DraftFieldTypes.To, draft.To, true);
                ValidateAddresses(DraftFieldTypes.Cc, draft.Cc, false);
                ValidateAddresses(DraftFieldTypes.Bcc, draft.Bcc, false);

                var scheme = HttpContext.Current == null ? Uri.UriSchemeHttp : HttpContext.Current.Request.GetUrlRewriter().Scheme;

                manager.SetDraftSending(draft);

                ThreadPool.QueueUserWorkItem(_ =>
                {
                    try
                    {
                        CoreContext.TenantManager.SetCurrentTenant(draft.Mailbox.TenantId);

                        SecurityContext.AuthenticateMe(new Guid(draft.Mailbox.UserId));

                        ApiHelper.SetupScheme(scheme);

                        draft.ChangeEmbededAttachmentLinks(log);

                        draft.ChangeSmileLinks(log);

                        draft.ChangeAttachedFileLinksAddresses(log);

                        draft.ChangeAttachedFileLinksImages(log);

                        var mimeMessage = draft.ToMimeMessage(true);

                        var smtp = MailClientBuilder.Smtp();

                        smtp.Send(draft.Mailbox, mimeMessage, log);

                        try
                        {
                            SendMailNotification(draft.Mailbox.TenantId, draft.Mailbox.UserId, 0);

                            manager.ReleaseSendingDraftOnSuccess(draft, message);

                            manager.AddRelationshipEventForLinkedAccounts(draft.Mailbox, message, log);

                            manager.SaveEmailInData(draft.Mailbox, message, log);

                            manager.SaveMailContacts(draft.Mailbox.TenantId, draft.Mailbox.UserId, mimeMessage);

                            StoreMessageToImapSentFolder(draft.Mailbox, mimeMessage);
                        }
                        catch (Exception ex)
                        {
                            log.Error("Unexpected Error in Send() Id = {0}\r\nException: {1}",
                                      message.Id, ex.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        AddNotificationAlertToMailbox(draft, ex);

                        manager.ReleaseSendingDraftOnFailure(draft);

                        SendMailNotification(draft.Mailbox.TenantId, draft.Mailbox.UserId, 1);
                    }
                });
            }
            else
            {
                throw new ArgumentException("Failed to_addresses save draft");
            }

            return(message.Id > 0 ? (Int32)message.Id : 1); // Callback in api will be raised if value > 0
        }