public CrmHistoryDal(MailBoxManager manager, int tenant_id, string user_id)
 {
     _manager = manager;
     _baseUrl = WebConfigurationManager.AppSettings["api.url"].Trim('~', '/');
     _tenant_id = tenant_id;
     _user_id = new Guid(user_id);
 }
 public MailItemManager(MailBoxManager mail_box_manager, List<MessageHandlerBase> message_handlers)
 {
     if (mail_box_manager == null) throw new ArgumentNullException("mail_box_manager");
     _mailBoxManager = mail_box_manager;
     _messageHandlers = message_handlers;
     _log = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Nlog, "MailItemManager");
 }
 public DocumentsDal(MailBoxManager manager, int tenant_id, string user_id)
 {
     _manager = manager;
     _tenantId = tenant_id;
     _userIdString = user_id;
     _userId = new Guid(user_id);
 }
        public CollectorService()
        {
            this.ServiceName = AscMailCollectionServiceName;
            this.EventLog.Log = "Application";

            // These Flags set whether or not to handle that specific
            // type of event. Set to true if you need it, false otherwise.
            this.CanHandlePowerEvent = false;
            this.CanHandleSessionChangeEvent = false;
            this.CanPauseAndContinue = false;
            this.CanShutdown = true;
            this.CanStop = true;
            try
            {
                _log = LogManager.GetLogger("CollectorService");
                _log.Info("Connecting to db...");
                _manger = new MailBoxManager(ConfigurationManager.ConnectionStrings["mail"], 25);
                _log.Info("Creating collector service...");
                _collector = new Collector(_manger, MailQueueSettings.FromConfig);
                _log.Info("Service is ready.");

                AggregatorLogger.Instance.Initialize(_manger, GetServiceIp());
                _log.Info("Aggregator logger initialized.");
            }
            catch (Exception ex)
            {
                _log.Fatal("CollectorService error under constuct: {0}", ex.ToString());
            }
        }
Exemple #5
0
        protected BaseWorker(MailBoxManager mailBoxManager, MailBox mailBox, TasksConfig tasksConfig,
                             CancellationToken cancelToken, ILogger log = null)
        {
            this.mailBoxManager = mailBoxManager;
            _mailBox = mailBox;
            this.log = log ?? new NullLogger();
            _lastTimeItemChecked = DateTime.UtcNow;
            _maxMessagesPerSession = tasksConfig.MaxMessagesPerSession;
            this.tasksConfig = tasksConfig;
            _signalrServiceClient = new SignalrServiceClient();

            _needSignal = false;

            this.cancelToken = cancelToken;

            if (tasksConfig.ShowActiveUpLogs)
            {
                Logger.Log4NetLogger = log4net.LogManager.GetLogger(string.Format("Task_{0}->ActiveUp", Task.CurrentId));
                Logger.Disabled = false;
            }
            else
            {
                Logger.Log4NetLogger = null;
                Logger.Disabled = true;
            }
        }
        public DocumentsDal(MailBoxManager manager, int tenant, string user)
        {
            _manager = manager;
            _tenantId = tenant;
            _userId = user;

            if (SecurityContext.IsAuthenticated) return;

            CoreContext.TenantManager.SetCurrentTenant(Tenant);
            SecurityContext.AuthenticateMe(new Guid(_userId));
        }
 public QueueManager(MailBoxManager mailBoxManager, TasksConfig tasksConfig, ILogger log = null)
 {
     _manager = mailBoxManager;
     _maxItemsLimit = tasksConfig.MaxTasksAtOnce;
     _mailBoxQueue = new Queue<MailBox>();
     _lockedMailBoxList = new List<MailBox>();
     _tasksConfig = tasksConfig;
     _log = log ?? new NullLogger();
     _loadQueueTime = DateTime.UtcNow;
     _tenantMemCache = new MemoryCache("QueueManagerTenantCache");
     CancelHandler = new ManualResetEvent(false);
 }
        public Collector(MailBoxManager manager, MailQueueSettings settings)
        {
            _log = LogManager.GetLogger("Collector");
            _manager = manager;
            _settings = settings;
            _itemManger = new MailItemManager(_manager);
            _queue = new MailWorkerQueue(settings.ConcurrentThreadCount, settings.CheckInterval, this);

            _log.Info("MailWorkerQueue: ConcurrentThreadCount = {0} and CheckInterval = {1}", 
                settings.ConcurrentThreadCount, settings.CheckInterval);

            
        }
        public Collector(MailBoxManager manager, MailQueueSettings settings, List<MessageHandlerBase> message_handlers) 
        {
            _log = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Nlog, "Collector");
            _manager = manager;
            _settings = settings;
            _itemManger = new MailItemManager(_manager, message_handlers);
            _queue = new MailWorkerQueue(settings.ConcurrentThreadCount, settings.CheckInterval, this);

            _log.Info("MailWorkerQueue: ConcurrentThreadCount = {0} and CheckInterval = {1}", 
                settings.ConcurrentThreadCount, settings.CheckInterval);

            if (settings.WorkOnUsersOnly != null && settings.WorkOnUsersOnly.Any())
            {
                var i = 0;
                var users = string.Empty;
                settings.WorkOnUsersOnly.ForEach(user => users += string.Format("\r\n\t\t\t\t{0}. \"{1}\"", ++i, user));

                _log.Info("Aggreagtor will get tasks for this users only:" + users);
            }
        }
Exemple #10
0
 public Pop3Worker(MailBoxManager mailBoxManager, MailBox mailBox, TasksConfig tasksConfig, CancellationToken cancelToken, ILogger log = null)
     : base(mailBoxManager, mailBox, tasksConfig, cancelToken, log)
 {
 }
 public IList <MailBoxManager.MailAlert> GetAlerts()
 {
     return(MailBoxManager.GetMailAlerts(TenantId, Username));
 }
        private MailBox ProcessMailbox(MailBox mailbox, TasksConfig tasksConfig, CancellationToken cancelToken)
        {
            var taskLogger = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Log4Net, "Task_" + Task.CurrentId);

            taskLogger.Info(
                "ProcessMailbox(Tenant = {0}, MailboxId = {1} Address = '{2}') Is {3}",
                mailbox.TenantId, mailbox.MailBoxId,
                mailbox.EMail, mailbox.Active ? "Active" : "Inactive");

            try
            {
                var manager = new MailBoxManager(taskLogger)
                {
                    AuthErrorWarningTimeout = tasksConfig.AuthErrorWarningTimeout,
                    AuthErrorDisableTimeout = tasksConfig.AuthErrorDisableMailboxTimeout
                };

                if (mailbox.Imap)
                {
                    using (var worker = new Imap4Worker(manager, mailbox, tasksConfig, cancelToken, taskLogger))
                    {
                        worker.Aggregate();
                    }
                }
                else
                {
                    using (var worker = new Pop3Worker(manager, mailbox, tasksConfig, cancelToken, taskLogger))
                    {
                        worker.Aggregate();
                    }
                }

                taskLogger.Info("Mailbox '{0}' has been processed.", mailbox.EMail);
            }
            catch (OperationCanceledException)
            {
                taskLogger.Info("Task canceled.");
                throw;
            }
            catch (Exception ex)
            {
                taskLogger.Error(
                    "ProcessMailbox(Tenant = {0}, MailboxId = {1}, Address = '{2}')\r\nException: {3}\r\n",
                    mailbox.TenantId, mailbox.MailBoxId, mailbox.EMail, ex.ToString());
            }

            return mailbox;
        }
Exemple #13
0
        public void TestForMultiplePointInDomainCase()
        {
            var result = MailBoxManager.GetLoginFormatFrom(new MailAddress("*****@*****.**"), "eQUal.nOtequal");

            Assert.AreEqual("%EMAILLOCALPART%.%EMAILHOSTNAME%", result);
        }
Exemple #14
0
        public void TestForGmailAnalguesCase()
        {
            var result = MailBoxManager.GetLoginFormatFrom(new MailAddress("*****@*****.**"), "recent:[email protected]");

            Assert.AreEqual("recent:%EMAILADDRESS%", result);
        }
 public EmailInMessageHandler(ILogger log, string connection_string_name)
     : base(log, connection_string_name)
 {
     mail_box_manager = new MailBoxManager(0, log);
 }
 public Imap4Worker(MailBoxManager mailBoxManager, MailBox mailBox, TasksConfig tasksConfig, CancellationToken cancelToken, bool loadOriginalEml, ILogger log = null)
     : base(mailBoxManager, mailBox, tasksConfig, cancelToken, log)
 {
     LoadOriginalEmlData = loadOriginalEml;
 }
Exemple #17
0
        private static MailBox GetMailBox(int mailboxId)
        {
            var manager = new MailBoxManager(new NullLogger());

            return(manager.GetMailBox(mailboxId));
        }
 public Imap4Worker(MailBoxManager mailBoxManager, MailBox mailBox, TasksConfig tasksConfig, CancellationToken cancelToken, ILogger log = null)
     : base(mailBoxManager, mailBox, tasksConfig, cancelToken, log)
 {
 }
        public void Init()
        {
            var startDate = DateTime.Now;

            var email = string.Format("1test_{0}_{1}_{2}_{3}@{4}",
                                      startDate.Day, startDate.Month, startDate.Year,
                                      startDate.Ticks, DOMAIN);

            var userInfo = new UserInfo
            {
                ID               = Guid.NewGuid(),
                UserName         = "******" + startDate,
                FirstName        = "Test_FirstName_" + startDate,
                LastName         = "Test_LastName_" + startDate,
                Email            = email,
                BirthDate        = startDate,
                WorkFromDate     = startDate,
                Status           = EmployeeStatus.Active,
                ActivationStatus = EmployeeActivationStatus.Activated
            };

            var emailUser2 = string.Format("2test_{0}_{1}_{2}_{3}@{4}",
                                           startDate.Day, startDate.Month, startDate.Year,
                                           startDate.Ticks, DOMAIN);

            var userInfo2 = new UserInfo
            {
                ID               = Guid.NewGuid(),
                UserName         = "******" + startDate,
                FirstName        = "Test_FirstName_" + startDate,
                LastName         = "Test_LastName_" + startDate,
                Email            = emailUser2,
                BirthDate        = startDate,
                WorkFromDate     = startDate,
                Status           = EmployeeStatus.Active,
                ActivationStatus = EmployeeActivationStatus.Activated
            };

            CoreContext.TenantManager.SetCurrentTenant(CURRENT_TENANT);

            SecurityContext.AuthenticateMe(Core.Configuration.Constants.CoreSystem);

            TestUser1 = CoreContext.UserManager.SaveUserInfo(userInfo);

            SecurityContext.SetUserPassword(TestUser1.ID, PASSWORD);

            TestUser2 = CoreContext.UserManager.SaveUserInfo(userInfo2);

            SecurityContext.SetUserPassword(TestUser2.ID, PASSWORD);

            _mailBoxManager = new MailBoxManager();

            var mailboxSettings = _mailBoxManager.GetMailBoxSettings(DOMAIN);

            var testMailboxes = mailboxSettings.ToMailboxList(email, PASSWORD, CURRENT_TENANT, TestUser1.ID.ToString());

            var mbox = testMailboxes.FirstOrDefault();

            if (!_mailBoxManager.SaveMailBox(mbox))
            {
                throw new Exception(string.Format("Can't create mailbox with email: {0}", email));
            }

            testMailboxes = mailboxSettings.ToMailboxList(emailUser2, PASSWORD, CURRENT_TENANT, TestUser2.ID.ToString());

            var mboxUser2 = testMailboxes.FirstOrDefault();

            if (!_mailBoxManager.SaveMailBox(mboxUser2))
            {
                throw new Exception(string.Format("Can't create mailbox with email: {0}", emailUser2));
            }

            TestUser2Mailboxes = new List <MailBox> {
                mboxUser2
            };

            var email2 = "*****@*****.**";

            var test2Mailboxes = mailboxSettings.ToMailboxList(email2, PASSWORD, CURRENT_TENANT, TestUser1.ID.ToString());

            var mbox2 = test2Mailboxes.FirstOrDefault();

            if (!_mailBoxManager.SaveMailBox(mbox2))
            {
                throw new Exception(string.Format("Can't create mailbox with email: {0}", email2));
            }

            var email3 = "*****@*****.**";

            var test3Mailboxes = mailboxSettings.ToMailboxList(email3, PASSWORD, CURRENT_TENANT, TestUser1.ID.ToString());

            var mbox3 = test3Mailboxes.FirstOrDefault();

            if (!_mailBoxManager.SaveMailBox(mbox3))
            {
                throw new Exception(string.Format("Can't create mailbox with email: {0}", email3));
            }

            TestUser1Mailboxes = new List <MailBox> {
                mbox, mbox2, mbox3
            };
        }
Exemple #20
0
        private static void TestConnectAccountSimple(string email, string password)
        {
            var mailBoxManager = new MailBoxManager(_log);

            var domain = email.Substring(email.IndexOf('@') + 1);

            _log.Debug("Search mailbox settings for domain '{0}'\r\n", domain);

            var mailboxSettings = mailBoxManager.GetMailBoxSettings(domain);

            if (mailboxSettings == null)
            {
                _log.Error("[TEST FAILED] Unknown mail provider settings.");
                return;
            }

            var testMailboxes = mailboxSettings.ToMailboxList(email, password, 0, Guid.NewGuid().ToString());

            var i = 0;

            foreach (var mbox in testMailboxes)
            {
                LoginResult loginResult;

                _log.Info("Attempt #{0} Account: '{1}' Password: '******'", ++i, mbox.Account, mbox.Password);

                _log.Debug("{0}Server: '{1}' Port: '{2}' AuthenticationType: '{3}' EncryptionType: '{4}'",
                           mbox.Imap ? "Imap" : "Pop",
                           mbox.Server,
                           mbox.Port,
                           mbox.Authentication,
                           mbox.Encryption);

                _log.Debug("SmtpServer: '{0}' Port: '{1}' AuthenticationType: '{2}' EncryptionType: '{3}'",
                           mbox.SmtpServer,
                           mbox.SmtpPort,
                           mbox.SmtpAuthentication,
                           mbox.SmtpEncryption);

                using (var client = new MailClient(mbox, CancellationToken.None, 5000,
                                                   _sslCertificatesErrorPermit))
                {
                    loginResult = client.TestLogin();
                }

                if (!loginResult.IngoingSuccess)
                {
                    _log.Error("{0} failed: '{1}'", mbox.Imap ? "Imap" : "Pop",
                               loginResult.IngoingException.Message + (loginResult.IngoingException.InnerException != null
                            ? " Inner Exception: " + loginResult.IngoingException.InnerException.Message
                            : ""));
                }
                else
                {
                    _log.Info("{0} succeeded", mbox.Imap ? "Imap" : "Pop");
                }

                if (!loginResult.OutgoingSuccess)
                {
                    _log.Error("Smtp failed: '{0}'\r\n",
                               loginResult.OutgoingException.Message + (loginResult.OutgoingException.InnerException != null
                            ? " Inner Exception: " + loginResult.OutgoingException.InnerException.Message
                            : ""));
                }
                else
                {
                    _log.Info("Smtp succeeded\r\n");
                }
            }
        }
Exemple #21
0
        public IEnumerable <MailContactData> GetContactsByContactInfo(ContactInfoType infoType, String data, bool?isPrimary)
        {
            var contacts = MailBoxManager.GetContactsByContactInfo(TenantId, Username, infoType, data, isPrimary);

            return(contacts.ToContactData());
        }
Exemple #22
0
        public MailRemoveMailserverMailboxOperation(Tenant tenant, IAccount user, IMailbox mailBox, MailBoxManager mailBoxManager, MailServerBase mailServer, IMailServerFactory mailServerFactory)
            : base(tenant, user)
        {
            _mailBox = mailBox;

            _mailBoxManager = mailBoxManager;

            _mailServer = mailServer;

            _mailServerFactory = mailServerFactory;

            SetSource(_mailBox.Id.ToString());
        }
Exemple #23
0
 public IEnumerable <MailTagData> GetTags()
 {
     return(MailBoxManager.GetTags(TenantId, Username, false).ToList().ToTagData());
 }
 // Constructor
 public MailboxIterator(MailBoxManager mailBoxManager)
 {
     _mailBoxManager = mailBoxManager;
     _mailBoxManager.GetMailboxesRange(out _minMailboxId, out _maxMailboxId);
 }
Exemple #25
0
        public MailAccountData CreateAccount(string name,
                                             string email,
                                             string account,
                                             string password,
                                             int port,
                                             string server,
                                             string smtp_account,
                                             string smtp_password,
                                             int smtp_port,
                                             string smtp_server,
                                             bool smtp_auth,
                                             bool imap,
                                             bool restrict,
                                             EncryptionType incoming_encryption_type,
                                             EncryptionType outcoming_encryption_type,
                                             SaslMechanism auth_type_in,
                                             SaslMechanism auth_type_smtp)
        {
            string errorText = null;
            var    mbox      = new MailBox
            {
                Name         = name,
                EMail        = new MailAddress(email),
                Account      = account,
                Password     = password,
                Port         = port,
                Server       = server,
                SmtpAccount  = smtp_account,
                SmtpPassword = smtp_password,
                SmtpPort     = smtp_port,
                SmtpServer   = smtp_server,
                SmtpAuth     = smtp_auth,
                Imap         = imap,
                Restrict     = restrict,
                TenantId     = TenantId,
                UserId       = Username,
                BeginDate    = restrict ?
                               DateTime.Now.Subtract(new TimeSpan(MailBox.DefaultMailLimitedTimeDelta)) :
                               new DateTime(MailBox.DefaultMailBeginTimestamp),
                IncomingEncryptionType  = incoming_encryption_type,
                OutcomingEncryptionType = outcoming_encryption_type,
                AuthenticationTypeIn    = auth_type_in,
                AuthenticationTypeSmtp  = auth_type_smtp
            };

            try
            {
                MailServerHelper.Test(mbox);
            }
            catch (ImapConnectionException exImap)
            {
                errorText = GetFormattedTextError(exImap, ServerType.Imap, exImap is ImapConnectionTimeoutException);
            }
            catch (Pop3ConnectionException exPop3)
            {
                errorText = GetFormattedTextError(exPop3, ServerType.Pop3, exPop3 is Pop3ConnectionTimeoutException);
            }
            catch (SmtpConnectionException exSmtp)
            {
                errorText = GetFormattedTextError(exSmtp, ServerType.Smtp, exSmtp is SmtpConnectionTimeoutException);
            }
            catch (Exception ex)
            {
                errorText = GetFormattedTextError(ex);
            }

            if (!string.IsNullOrEmpty(errorText))
            {
                throw new Exception(errorText);
            }

            try
            {
                mbox.InServerId = MailBoxManager.SaveMailServerSettings(mbox.EMail,
                                                                        new MailServerSettings
                {
                    AccountName        = mbox.Account,
                    AccountPass        = mbox.Password,
                    AuthenticationType =
                        mbox.AuthenticationTypeIn,
                    EncryptionType =
                        mbox.IncomingEncryptionType,
                    Port = mbox.Port,
                    Url  = mbox.Server
                },
                                                                        imap ? "imap" : "pop3",
                                                                        AuthorizationServiceType.Unknown);
                mbox.SmtpServerId = MailBoxManager.SaveMailServerSettings(mbox.EMail,
                                                                          new MailServerSettings
                {
                    AccountName        = mbox.SmtpAccount,
                    AccountPass        = mbox.SmtpPassword,
                    AuthenticationType =
                        mbox.AuthenticationTypeSmtp,
                    EncryptionType =
                        mbox.OutcomingEncryptionType,
                    Port = mbox.SmtpPort,
                    Url  = mbox.SmtpServer
                },
                                                                          "smtp", AuthorizationServiceType.Unknown);

                MailBoxManager.SaveMailBox(mbox);
                var accountInfo = new AccountInfo(mbox.MailBoxId, mbox.EMailView, mbox.Name, mbox.Enabled, mbox.QuotaError,
                                                  MailBox.AuthProblemType.NoProblems, new SignatureDto(mbox.MailBoxId, TenantId, "", false),
                                                  false, mbox.EMailInFolder, false, false);

                return(accountInfo.ToAddressData().FirstOrDefault());
            }
            catch (Exception ex)
            {
                //TODO: change AttachmentsUnknownError to common unknown error text
                errorText = GetFormattedTextError(ex, MailApiResource.AttachmentsUnknownError);
            }

            throw new Exception(errorText);
        }
        private void ClientOnGetMessage(object sender, MailClientMessageEventArgs mailClientMessageEventArgs)
        {
            var log = _log;

            try
            {
                var mimeMessage = mailClientMessageEventArgs.Message;
                var uid         = mailClientMessageEventArgs.MessageUid;
                var folder      = mailClientMessageEventArgs.Folder;
                var mailbox     = mailClientMessageEventArgs.Mailbox;
                var unread      = mailClientMessageEventArgs.Unread;
                var fromEmail   = mimeMessage.From.Mailboxes.FirstOrDefault();
                log = mailClientMessageEventArgs.Logger;

                var manager = new MailBoxManager(log);

                var md5 = string.Format("{0}|{1}|{2}|{3}",
                                        mimeMessage.From.Mailboxes.Any() ? mimeMessage.From.Mailboxes.First().Address : "",
                                        mimeMessage.Subject,
                                        mimeMessage.Date.UtcDateTime,
                                        mimeMessage.MessageId)
                          .GetMd5();

                var uidl = mailbox.Imap ? string.Format("{0}-{1}", uid, folder.FolderId) : uid;

                var fromThisMailBox =
                    fromEmail != null &&
                    fromEmail.Address.ToLowerInvariant().Equals(mailbox.EMail.Address.ToLowerInvariant());

                var toThisMailBox =
                    mimeMessage.To.Mailboxes.Select(addr => addr.Address.ToLowerInvariant())
                    .Contains(mailbox.EMail.Address.ToLowerInvariant());

                log.Info(@"Message:
    MimeId:   '{0}'
    Subject:  '{1}'
    Date:     {2}
    FolderId: {3} ('{4}')
    Unread:   {5}
    Uidl:     '{6}'
    Md5:      '{7}'
    To->From: {8}
    From->To: {9}",
                         mimeMessage.MessageId,
                         mimeMessage.Subject,
                         mimeMessage.Date,
                         folder.FolderId,
                         folder.Name,
                         unread,
                         uidl,
                         md5,
                         fromThisMailBox,
                         toThisMailBox);

                var tagsIds = folder.Tags.Any() ? manager.GetOrCreateTags(mailbox.TenantId, mailbox.UserId, folder.Tags) : null;

                var found = manager
                            .SearchExistingMessagesAndUpdateIfNeeded(
                    mailbox,
                    folder.FolderId,
                    uidl,
                    md5,
                    mimeMessage.MessageId,
                    fromThisMailBox,
                    toThisMailBox,
                    tagsIds);

                var needSave = !found;
                if (!needSave)
                {
                    return;
                }

                var chainId = manager.DetectChainId(mailbox, mimeMessage.MessageId, mimeMessage.InReplyTo,
                                                    mimeMessage.Subject);

                var streamId = MailUtil.CreateStreamId();

                log.Debug("MimeMessage->MailMessage");

                var message = new MailMessage(mimeMessage, folder.FolderId, unread, chainId, streamId);

                if (!TryStoreMailData(message, mailbox, log))
                {
                    return;
                }

                log.Debug("MailSave()");

                var folderRestoreId = folder.FolderId == MailFolder.Ids.spam ? MailFolder.Ids.inbox : folder.FolderId;

                message.Id = manager.MailSave(mailbox, message, 0, folder.FolderId, folderRestoreId, uidl, md5, true);

                log.Info("MailSave(Account:{0}) returned mailId = {1}\r\n", mailbox.EMail, message.Id);

                log.Debug("DoOptionalOperations()");

                DoOptionalOperations(message, mimeMessage, mailbox, tagsIds, log);

                bool     isMailboxRemoved;
                bool     isMailboxDeactivated;
                DateTime beginDate;

                manager.GetMailBoxState(mailbox.MailBoxId, out isMailboxRemoved, out isMailboxDeactivated, out beginDate);

                if (mailbox.BeginDate != beginDate)
                {
                    mailbox.BeginDateChanged = true;
                    mailbox.BeginDate        = beginDate;
                }

                var client = sender as MailClient;

                if (isMailboxRemoved)
                {
                    if (client != null)
                    {
                        client.Cancel();
                    }

                    manager.DeleteMessages(
                        mailbox.TenantId,
                        mailbox.UserId,
                        new List <int>
                    {
                        (int)message.Id
                    });

                    log.Info("MailBox with id={0} is removed.\r\n", mailbox.MailBoxId);
                }

                if (isMailboxDeactivated)
                {
                    if (client != null)
                    {
                        client.Cancel();
                    }

                    log.Info("MailBox with id={0} is deactivated.\r\n", mailbox.MailBoxId);
                }
            }
            catch (Exception ex)
            {
                log.Error("[ClientOnGetMessage] Exception:\r\n{0}\r\n", ex.ToString());
            }
        }
Exemple #27
0
        public MailAccountData UpdateAccount(string name,
                                             string email,
                                             string account,
                                             string password,
                                             int port,
                                             string server,
                                             string smtp_account,
                                             string smtp_password,
                                             int smtp_port,
                                             string smtp_server,
                                             bool smtp_auth,
                                             bool restrict,
                                             EncryptionType incoming_encryption_type,
                                             EncryptionType outcoming_encryption_type,
                                             SaslMechanism auth_type_in,
                                             SaslMechanism auth_type_smtp)
        {
            if (string.IsNullOrEmpty(email))
            {
                throw new ArgumentException();
            }

            var mbox = MailBoxManager.GetMailBox(TenantId, Username, new MailAddress(email));

            if (null == mbox)
            {
                throw new ArgumentException("Mailbox with specified email doesn't exist.");
            }

            if (mbox.IsTeamlab)
            {
                throw new ArgumentException("Mailbox with specified email can't be updated");
            }

            if (string.IsNullOrEmpty(password))
            {
                password = mbox.Password;
            }
            if (string.IsNullOrEmpty(smtp_password))
            {
                smtp_password = mbox.SmtpPassword;
            }

            string errorText;

            mbox.Account      = account;
            mbox.Name         = name;
            mbox.Password     = password;
            mbox.SmtpAccount  = smtp_account;
            mbox.SmtpPassword = smtp_password;
            mbox.Port         = port;
            mbox.Server       = server;
            mbox.SmtpPort     = smtp_port;
            mbox.SmtpServer   = smtp_server;
            mbox.SmtpAuth     = smtp_auth;
            mbox.Restrict     = restrict;
            mbox.BeginDate    = mbox.Restrict ?
                                DateTime.Now.Subtract(new TimeSpan(mbox.MailLimitedTimeDelta)) :
                                mbox.MailBeginTimestamp;
            mbox.IncomingEncryptionType  = incoming_encryption_type;
            mbox.OutcomingEncryptionType = outcoming_encryption_type;
            mbox.AuthenticationTypeIn    = auth_type_in;
            mbox.AuthenticationTypeSmtp  = auth_type_smtp;

            mbox.InServerId = MailBoxManager.SaveMailServerSettings(mbox.EMail,
                                                                    new MailServerSettings
            {
                AccountName        = mbox.Account,
                AccountPass        = mbox.Password,
                AuthenticationType = mbox.AuthenticationTypeIn,
                EncryptionType     = mbox.IncomingEncryptionType,
                Port = mbox.Port,
                Url  = mbox.Server
            },
                                                                    mbox.Imap ? "imap" : "pop3", AuthorizationServiceType.Unknown);
            mbox.SmtpServerId = MailBoxManager.SaveMailServerSettings(mbox.EMail,
                                                                      new MailServerSettings
            {
                AccountName        = mbox.SmtpAccount,
                AccountPass        = mbox.SmtpPassword,
                AuthenticationType = mbox.AuthenticationTypeSmtp,
                EncryptionType     = mbox.OutcomingEncryptionType,
                Port = mbox.SmtpPort,
                Url  = mbox.SmtpServer
            },
                                                                      "smtp", AuthorizationServiceType.Unknown);

            try
            {
                if (!string.IsNullOrEmpty(mbox.RefreshToken) || MailServerHelper.Test(mbox))
                {
                    if (!MailBoxManager.SaveMailBox(mbox))
                    {
                        throw new Exception("Failed to_addresses update account");
                    }
                }

                var accountInfo = new AccountInfo(mbox.MailBoxId, mbox.EMailView, mbox.Name, mbox.Enabled, mbox.QuotaError,
                                                  MailBox.AuthProblemType.NoProblems, new SignatureDto(mbox.MailBoxId, TenantId, "", false),
                                                  false, mbox.EMailInFolder, false, false);

                return(accountInfo.ToAddressData().FirstOrDefault());
            }
            catch (ImapConnectionException exImap)
            {
                errorText = GetFormattedTextError(exImap, ServerType.Imap, exImap is ImapConnectionTimeoutException);
            }
            catch (Pop3ConnectionException exPop3)
            {
                errorText = GetFormattedTextError(exPop3, ServerType.Pop3, exPop3 is Pop3ConnectionTimeoutException);
            }
            catch (SmtpConnectionException exSmtp)
            {
                errorText = GetFormattedTextError(exSmtp, ServerType.Smtp, exSmtp is SmtpConnectionTimeoutException);
            }
            catch (Exception ex)
            {
                errorText = GetFormattedTextError(ex);
            }

            throw new Exception(errorText);
        }
 // Constructor
 public MailboxIterator(MailBoxManager mailBoxManager)
 {
     _mailBoxManager = mailBoxManager;
     _mailBoxManager.GetMailboxesRange(out _minMailboxId, out _maxMailboxId);
 }
Exemple #29
0
        public IEnumerable <MailAccountData> GetAccounts()
        {
            var accounts = MailBoxManager.GetAccountInfo(TenantId, Username);

            return(accounts.ToAddressData());
        }
Exemple #30
0
        public void TestForEqualLocalpartAndDomainNameCase()
        {
            var result = MailBoxManager.GetLoginFormatFrom(new MailAddress("*****@*****.**"), "EquaL.EQual");

            Assert.AreEqual("%EMAILLOCALPART%.%EMAILHOSTNAME%", result);
        }
Exemple #31
0
        public MailAccountData CreateAccountSimple(string email, string password)
        {
            if (string.IsNullOrEmpty(email))
            {
                throw new ArgumentException(@"Empty email", "email");
            }

            string  errorText = null;
            MailBox mbox      = null;

            try
            {
                mbox = MailBoxManager.SearchMailboxSettings(email, password, Username, TenantId);
            }
            catch (ImapConnectionException exImap)
            {
                errorText = GetFormattedTextError(exImap, ServerType.Imap, exImap is ImapConnectionTimeoutException);
            }
            catch (Pop3ConnectionException exPop)
            {
                errorText = GetFormattedTextError(exPop, ServerType.Pop3, exPop is Pop3ConnectionTimeoutException);
            }
            catch (SmtpConnectionException exSmtp)
            {
                errorText = GetFormattedTextError(exSmtp, ServerType.Smtp, exSmtp is SmtpConnectionTimeoutException);
            }
            catch (ItemNotFoundException exProvider)
            {
                errorText = GetFormattedTextError(exProvider);
            }
            catch (Exception ex)
            {
                errorText = GetFormattedTextError(ex);
            }

            if (!string.IsNullOrEmpty(errorText))
            {
                throw new Exception(errorText);
            }

            try
            {
                if (mbox == null)
                {
                    throw new Exception();
                }

                mbox.InServerId = MailBoxManager.SaveMailServerSettings(mbox.EMail,
                                                                        new MailServerSettings
                {
                    AccountName        = mbox.Account,
                    AccountPass        = mbox.Password,
                    AuthenticationType =
                        mbox.AuthenticationTypeIn,
                    EncryptionType =
                        mbox.IncomingEncryptionType,
                    Port = mbox.Port,
                    Url  = mbox.Server
                },
                                                                        mbox.Imap ? "imap" : "pop3",
                                                                        AuthorizationServiceType.Unknown);

                mbox.SmtpServerId = MailBoxManager.SaveMailServerSettings(mbox.EMail,
                                                                          new MailServerSettings
                {
                    AccountName        = mbox.SmtpAccount,
                    AccountPass        = mbox.SmtpPassword,
                    AuthenticationType =
                        mbox.AuthenticationTypeSmtp,
                    EncryptionType =
                        mbox.OutcomingEncryptionType,
                    Port = mbox.SmtpPort,
                    Url  = mbox.SmtpServer
                },
                                                                          "smtp", AuthorizationServiceType.Unknown);

                MailBoxManager.SaveMailBox(mbox);
                var account = new AccountInfo(mbox.MailBoxId, mbox.EMailView, mbox.Name, mbox.Enabled, mbox.QuotaError,
                                              MailBox.AuthProblemType.NoProblems, new SignatureDto(mbox.MailBoxId, TenantId, "", false),
                                              false, mbox.EMailInFolder, false, false);

                return(account.ToAddressData().FirstOrDefault());
            }
            catch (Exception ex)
            {
                //TODO: change AttachmentsUnknownError to common unknown error text
                errorText = GetFormattedTextError(ex, MailApiResource.AttachmentsUnknownError);
            }

            throw new Exception(errorText);
        }
Exemple #32
0
        public void TestForMultiplePointInDomain2Case()
        {
            var result = MailBoxManager.GetLoginFormatFrom(new MailAddress("*****@*****.**"), "eQual.notequaL.mail.PaLa");

            Assert.AreEqual("%EMAILLOCALPART%.%EMAILHOSTNAME%", result);
        }
 public IEnumerable <MailTag> GetTags()
 {
     return(MailBoxManager.GetTagsList(TenantId, Username, false));
 }
        private void ShowMessages()
        {
            lvwMessages.Items.Clear();
            string messagesFolder = PayrollStatic.EmployeesFolder + "\\" + _Employee.FolderName + "\\Messages";

            if (!Directory.Exists(messagesFolder))
            {
                return;
            }
            if (_Employee.UseIMAP4)
            {
                // Authentication errors throw an exception
                ShowProgress("Logging in to mail server...");
                try
                {
                    // Have to make new IMap4Repository every time we check,
                    // because IMAP server will close connection after a short period of inactivity.
                    IMap4Repository imapRep;
                    imapRep = new IMap4Repository(
                        _Employee.IMAP4Host.GetValue,
                        _Employee.IMAP4Port.GetValue,
                        _Employee.IMAP4SSL.GetValue,
                        _Employee.IMAP4Address.GetValue,
                        _Employee.IMAP4Password.GetValue);
                    FileMailBoxCache inboxCache   = new PayrollMailBoxCache("inbox", messagesFolder);
                    MailBoxManager   inboxManager = new MailBoxManager(imapRep, inboxCache);
                    inboxManager.ProgressEvent += ShowProgress;
                    inboxManager.Init();
                    inboxManager.Refresh();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            ShowProgress("");
            List <Message> messages = new List <Message>();

            foreach (string fileName in Directory.GetFiles(messagesFolder))
            {
                bool isUnreadMessage = fileName.EndsWith(Message.UnreadExtension);
                bool isReadMessage   = fileName.EndsWith(Message.ReadExtension);
                if (isReadMessage || isUnreadMessage)
                {
                    try
                    {
                        XmlDocument msgDoc = new XmlDocument();
                        msgDoc.Load(fileName);
                        Message message = new Message(msgDoc, fileName);
                        if (DateTime.Now.Subtract(message.SendDateTime).TotalDays < 30 || isUnreadMessage)
                        {
                            messages.Add(message);
                        }
                        else
                        {
                            File.Delete(fileName);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error reading message file [" + fileName + "]: " + ex.Message);
                    }
                }
            }
            messages.Sort(
                delegate(Message msg1, Message msg2)
            {
                return(msg2.SendDateTime.CompareTo(msg1.SendDateTime));
            });
            foreach (Message message in messages)
            {
                ListViewItem msgItem = new ListViewItem(
                    new string[] {
                    message.SendDateTime.ToShortDateString(),
                    message.Subject,
                    message.Sender.ShortFormat
                });
                msgItem.Tag = message;
                if (message.SourceFile.EndsWith(Message.UnreadExtension))
                {
                    msgItem.BackColor = Color.Pink;
                }
                lvwMessages.Items.Add(msgItem);
            }
        }
Exemple #35
0
 public MailSendQueue(MailBoxManager manager)
 {
     _manager = manager;
 }
 public MailGarbageCleanDal(MailBoxManager manager)
 {
     _manager = manager;
 }
 public void Setup()
 {
     mailBoxManager = new MailBoxManager(30);
 }
        public AggregatorService(IEnumerable<string> workOnThisUsersOnly = null)
        {
            ServiceName = AscMailCollectionServiceName;
            EventLog.Log = "Application";

            // These Flags set whether or not to handle that specific
            // type of event. Set to true if you need it, false otherwise.
            CanHandlePowerEvent = false;
            CanHandleSessionChangeEvent = false;
            CanPauseAndContinue = false;
            CanShutdown = true;
            CanStop = true;
            try
            {
                XmlConfigurator.Configure();

                _log = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Log4Net, "MainThread");

                Environment.SetEnvironmentVariable("MONO_TLS_SESSION_CACHE_TIMEOUT", "0");

                _queueSettings = MailQueueSettings.FromConfig;
                
                if (workOnThisUsersOnly != null)
                    _queueSettings.WorkOnUsersOnly = workOnThisUsersOnly.ToList();
                else
                {
                    var userToWorkOn = ConfigurationManager.AppSettings["mail.OneUserMode"];
                    if (!string.IsNullOrEmpty(userToWorkOn))
                        _queueSettings.WorkOnUsersOnly.Add(userToWorkOn);
                }

                var authErrorWarningTimeout =
                    ConfigurationManager.AppSettings["mail.auth-error-warning-in-minutes"] != null
                        ? TimeSpan.FromMinutes(
                            Convert.ToInt32(ConfigurationManager.AppSettings["mail.auth-error-warning-in-minutes"]))
                        : TimeSpan.FromHours(1);

                _log.Info("Auth login error warning timeout is {0}.", authErrorWarningTimeout.ToString());

                var authErrorDisableMailboxTimeout =
                    ConfigurationManager.AppSettings["mail.auth-error-disable-mailbox-in-minutes"] != null
                        ? TimeSpan.FromMinutes(
                            Convert.ToInt32(ConfigurationManager.AppSettings["mail.auth-error-disable-mailbox-in-minutes"]))
                        : TimeSpan.FromDays(3);

                _log.Info("Auth login error disable mailbox timeout is {0}.", authErrorDisableMailboxTimeout.ToString());

                _log.Info("MailWorkerQueue: ConcurrentThreadCount = {0} and CheckInterval = {1} CheckPOP3_UIDL_Chunck = {2}",
                _queueSettings.ConcurrentThreadCount, _queueSettings.CheckInterval, _queueSettings.CheckPop3UidlChunk);

                var configBuilder = new TasksConfig.Builder();

                if (_queueSettings.WorkOnUsersOnly != null && _queueSettings.WorkOnUsersOnly.Any())
                {
                    var i = 0;
                    var users = string.Empty;
                    _queueSettings.WorkOnUsersOnly.ForEach(user => users += string.Format("\r\n\t\t\t\t{0}. \"{1}\"", ++i, user));

                    _log.Info("Aggregator will get tasks for this users only:" + users);
                }

                var queueLifetime = ConfigurationManager.AppSettings["mail.queue-lifetime-seconds"] != null
                        ? TimeSpan.FromSeconds(
                            Convert.ToInt32(ConfigurationManager.AppSettings["mail.queue-lifetime-seconds"]))
                        : TimeSpan.FromSeconds(30);

                var showActiveUpLogs = ConfigurationManager.AppSettings["mail.show-activeup-logs"] != null &&
                                       Convert.ToBoolean(
                                           ConfigurationManager.AppSettings["mail.show-activeup-logs"]);

                _tasksConfig = configBuilder.SetUsersToWorkOn(_queueSettings.WorkOnUsersOnly)
                                            .SetOnlyTeamlabTasks(_queueSettings.OnlyTeamlabTasks)
                                            .SetActiveInterval(_queueSettings.ActivityTimeout)
                                            .SetChunkOfPop3CheckUidLinDb(_queueSettings.CheckPop3UidlChunk)
                                            .SetEnableSignalr(_queueSettings.EnableSignalr)
                                            .SetMaxMessagesPerSession(_queueSettings.MaxMessagesPerSession)
                                            .SetMaxTasksAtOnce(_queueSettings.ConcurrentThreadCount)
                                            .SetQueueLifetime(queueLifetime)
                                            .SetTenantCachingPeriod(_queueSettings.TenantCachingPeriod)
                                            .SetShowActiveUpLogs(showActiveUpLogs)
                                            .SetInactiveMailboxesRatio(_queueSettings.InactiveMailboxesRatio)
                                            .SetAuthErrorWarningTimeout(authErrorWarningTimeout)
                                            .SetAuthErrorDisableMailboxTimeout(authErrorDisableMailboxTimeout)
                                            .Build();

                _tsInterval = _queueSettings.CheckInterval;

                _manager = new MailBoxManager(_log)
                {
                    AuthErrorWarningTimeout = _tasksConfig.AuthErrorWarningTimeout,
                    AuthErrorDisableTimeout = _tasksConfig.AuthErrorDisableMailboxTimeout
                };

                _queueManager = new QueueManager(_manager, _tasksConfig, _log);

                _resetEvent = new ManualResetEvent(false);

                _cancelTokenSource = new CancellationTokenSource();

                _lcts = new LimitedConcurrencyLevelTaskScheduler(_tasksConfig.MaxTasksAtOnce);

                _taskFactory = new TaskFactory(_lcts);

                _tsTaskStateCheckInterval = ConfigurationManager.AppSettings["mail.task-check-state-seconds"] != null
                        ? TimeSpan.FromSeconds(
                            Convert.ToInt32(ConfigurationManager.AppSettings["mail.task-check-state-seconds"]))
                        : TimeSpan.FromSeconds(30);

                if (ConfigurationManager.AppSettings["mail.default-api-scheme"] != null)
                {
                    var defaultApiScheme = ConfigurationManager.AppSettings["mail.default-api-scheme"];

                    ApiHelper.SetupScheme(defaultApiScheme);
                }

                _log.Info("Service is ready.");
            }
            catch (Exception ex)
            {
                _log.Fatal("CollectorService error under construct: {0}", ex.ToString());
            }
        }
 // Constructor
 public MailboxMessagesIterator(MailBox mailBox, MailBoxManager mailBoxManager)
 {
     _currentMailBox = mailBox;
     _mailBoxManager = mailBoxManager;
     _mailBoxManager.GetMailboxMessagesRange(_currentMailBox, out _minMessageId, out _maxMessageId);
 }
 // Constructor
 public MailboxMessagesIterator(MailBox mailBox, MailBoxManager mailBoxManager)
 {
     _currentMailBox = mailBox;
     _mailBoxManager = mailBoxManager;
     _mailBoxManager.GetMailboxMessagesRange(_currentMailBox, out _minMessageId, out _maxMessageId);
 }
Exemple #41
0
        public MailAccountData CreateAccount(string name,
                                             string email,
                                             string account,
                                             string password,
                                             int port,
                                             string server,
                                             string smtp_account,
                                             string smtp_password,
                                             int smtp_port,
                                             string smtp_server,
                                             bool smtp_auth,
                                             bool imap,
                                             bool restrict,
                                             EncryptionType incoming_encryption_type,
                                             EncryptionType outcoming_encryption_type,
                                             SaslMechanism auth_type_in,
                                             SaslMechanism auth_type_smtp)
        {
            string errorText = null;
            var    mbox      = new MailBox
            {
                Name         = name,
                EMail        = new MailAddress(email),
                Account      = account,
                Password     = password,
                Port         = port,
                Server       = server,
                SmtpAccount  = smtp_account,
                SmtpPassword = smtp_password,
                SmtpPort     = smtp_port,
                SmtpServer   = smtp_server,
                Imap         = imap,
                TenantId     = TenantId,
                UserId       = Username,
                BeginDate    = restrict ?
                               DateTime.Now.Subtract(new TimeSpan(MailBox.DefaultMailLimitedTimeDelta)) :
                               new DateTime(MailBox.DefaultMailBeginTimestamp),
                Encryption         = incoming_encryption_type,
                SmtpEncryption     = outcoming_encryption_type,
                Authentication     = auth_type_in,
                SmtpAuthentication = smtp_auth ? auth_type_smtp : SaslMechanism.None
            };

            LoginResult loginResult;

            using (var client = new MailClient(mbox, CancellationToken.None, 5000, SslCertificatesErrorPermit, log: _log))
            {
                loginResult = client.TestLogin();
            }

            if (!loginResult.IngoingSuccess)
            {
                errorText = GetFormattedTextError(loginResult.IngoingException,
                                                  mbox.Imap ? MailServerType.Imap : MailServerType.Pop3, false); // exImap is ImapConnectionTimeoutException
            }

            if (!loginResult.OutgoingSuccess)
            {
                if (!string.IsNullOrEmpty(errorText))
                {
                    errorText += "\r\n";
                }

                errorText += GetFormattedTextError(loginResult.OutgoingException, MailServerType.Smtp, false);
                // exSmtp is SmtpConnectionTimeoutException);
            }

            if (!string.IsNullOrEmpty(errorText))
            {
                throw new Exception(errorText);
            }

            try
            {
                MailBoxManager.SaveMailBox(mbox);
                MailBoxManager.CachedAccounts.Clear(Username);

                if (IsSignalRAvailable)
                {
                    MailBoxManager.UpdateUserActivity(TenantId, Username);
                }

                var accountInfo = new AccountInfo(mbox.MailBoxId, mbox.EMailView, mbox.Name, mbox.Enabled, mbox.QuotaError,
                                                  MailBox.AuthProblemType.NoProblems, new MailSignature(mbox.MailBoxId, TenantId, "", false),
                                                  new MailAutoreply(mbox.MailBoxId, TenantId, false, false, false, DateTime.MinValue,
                                                                    DateTime.MinValue, String.Empty, String.Empty), false, mbox.EMailInFolder, false, false);

                return(accountInfo.ToAddressData().FirstOrDefault());
            }
            catch (Exception ex)
            {
                //TODO: change AttachmentsUnknownError to common unknown error text
                errorText = GetFormattedTextError(ex, MailApiResource.AttachmentsUnknownError);
            }

            throw new Exception(errorText);
        }
        private void DoOptionalOperations(MailMessage message, MimeMessage mimeMessage, MailBox mailbox, int[] tagIds, ILogger log)
        {
            var manager = new MailBoxManager(log);

            CoreContext.TenantManager.SetCurrentTenant(mailbox.TenantId);

            SecurityContext.AuthenticateMe(new Guid(mailbox.UserId));

            try
            {
                if (mailbox.Imap)
                {
                    if (tagIds != null) // Add new tags to existing messages
                    {
                        foreach (var tagId in tagIds)
                        {
                            manager.SetMessagesTag(mailbox.TenantId, mailbox.UserId, tagId, new[] { (int)message.Id });
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _log.Error("SetMessagesTag(tenant={0}, userId='{1}', messageId={2}, tagid = {3}) Exception:\r\n{4}\r\n",
                           mailbox.TenantId, mailbox.UserId, message.Id, e.ToString(), tagIds != null ? string.Join(",", tagIds) : "null");
            }

            manager.AddRelationshipEventForLinkedAccounts(mailbox, message, _tasksConfig.DefaultApiSchema, log);

            manager.SaveEmailInData(mailbox, message, _tasksConfig.DefaultApiSchema, log);

            manager.SendAutoreply(mailbox, message, _tasksConfig.DefaultApiSchema, log);

            manager.UploadIcsToCalendar(
                mailbox,
                message.CalendarId,
                message.CalendarUid,
                message.CalendarEventIcs,
                message.CalendarEventCharset,
                message.CalendarEventMimeType,
                mailbox.EMail.Address,
                _tasksConfig.DefaultApiSchema, log);

            if (_tasksConfig.SaveOriginalMessage)
            {
                StoreMailEml(mailbox.TenantId, mailbox.UserId, message.StreamId, mimeMessage, log);
            }

            if (!_tasksConfig.EnableSignalr)
            {
                return;
            }

            var now = DateTime.UtcNow;

            if (mailbox.LastSignalrNotify.HasValue &&
                !((now - mailbox.LastSignalrNotify.Value).TotalSeconds > SIGNALR_WAIT_SECONDS))
            {
                mailbox.LastSignalrNotifySkipped = true;
                return;
            }

            NotifySignalr(mailbox, log);

            mailbox.LastSignalrNotify        = now;
            mailbox.LastSignalrNotifySkipped = false;
        }
Exemple #43
0
        public MailAccountData UpdateAccount(string name,
                                             string email,
                                             string account,
                                             string password,
                                             int port,
                                             string server,
                                             string smtp_account,
                                             string smtp_password,
                                             int smtp_port,
                                             string smtp_server,
                                             bool smtp_auth,
                                             bool restrict,
                                             EncryptionType incoming_encryption_type,
                                             EncryptionType outcoming_encryption_type,
                                             SaslMechanism auth_type_in,
                                             SaslMechanism auth_type_smtp)
        {
            if (string.IsNullOrEmpty(email))
            {
                throw new ArgumentException();
            }

            var mbox = MailBoxManager.GetMailBox(TenantId, Username, new MailAddress(email));

            if (null == mbox)
            {
                throw new ArgumentException("Mailbox with specified email doesn't exist.");
            }

            if (mbox.IsTeamlab)
            {
                throw new ArgumentException("Mailbox with specified email can't be updated");
            }

            if (string.IsNullOrEmpty(password))
            {
                password = mbox.Password;
            }
            if (string.IsNullOrEmpty(smtp_password))
            {
                smtp_password = mbox.SmtpPassword;
            }

            string errorText = null;

            mbox.Account      = account;
            mbox.Name         = name;
            mbox.Password     = password;
            mbox.SmtpAccount  = smtp_account;
            mbox.SmtpPassword = smtp_password;
            mbox.Port         = port;
            mbox.Server       = server;
            mbox.SmtpPort     = smtp_port;
            mbox.SmtpServer   = smtp_server;

            mbox.BeginDate = restrict
                ? DateTime.Now.Subtract(new TimeSpan(mbox.MailLimitedTimeDelta))
                : mbox.MailBeginTimestamp;
            mbox.Encryption         = incoming_encryption_type;
            mbox.SmtpEncryption     = outcoming_encryption_type;
            mbox.Authentication     = auth_type_in;
            mbox.SmtpAuthentication = smtp_auth ? auth_type_smtp : SaslMechanism.None;

            try
            {
                if (string.IsNullOrEmpty(mbox.OAuthToken))
                {
                    LoginResult loginResult;

                    using (var client = new MailClient(mbox, CancellationToken.None, 5000, SslCertificatesErrorPermit, log: _log))
                    {
                        loginResult = client.TestLogin();
                    }

                    if (!loginResult.IngoingSuccess)
                    {
                        errorText = GetFormattedTextError(loginResult.IngoingException,
                                                          mbox.Imap ? MailServerType.Imap : MailServerType.Pop3, false); // exImap is ImapConnectionTimeoutException
                    }

                    if (!loginResult.OutgoingSuccess)
                    {
                        if (!string.IsNullOrEmpty(errorText))
                        {
                            errorText += "\r\n";
                        }

                        errorText += GetFormattedTextError(loginResult.OutgoingException, MailServerType.Smtp, false);
                        // exSmtp is SmtpConnectionTimeoutException);
                    }

                    if (!string.IsNullOrEmpty(errorText))
                    {
                        throw new Exception(errorText);
                    }
                }

                if (!MailBoxManager.SaveMailBox(mbox))
                {
                    throw new Exception("Failed to_addresses update account");
                }

                MailBoxManager.CachedAccounts.Clear(Username);

                var accountInfo = new AccountInfo(mbox.MailBoxId, mbox.EMailView, mbox.Name, mbox.Enabled, mbox.QuotaError,
                                                  MailBox.AuthProblemType.NoProblems, new MailSignature(mbox.MailBoxId, TenantId, "", false),
                                                  new MailAutoreply(mbox.MailBoxId, TenantId, false, false, false, DateTime.MinValue,
                                                                    DateTime.MinValue, String.Empty, String.Empty), false, mbox.EMailInFolder, false, false);

                return(accountInfo.ToAddressData().FirstOrDefault());
            }
            catch (Exception ex)
            {
                errorText = GetFormattedTextError(ex);
            }

            throw new Exception(errorText);
        }
        public CollectorService(IEnumerable<string> work_on_this_users_only = null)
        {
            ServiceName = asc_mail_collection_service_name;
            EventLog.Log = "Application";

            // These Flags set whether or not to handle that specific
            // type of event. Set to true if you need it, false otherwise.
            CanHandlePowerEvent = false;
            CanHandleSessionChangeEvent = false;
            CanPauseAndContinue = false;
            CanShutdown = true;
            CanStop = true;
            try
            {
                _log = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Nlog, "CollectorService");

                _log.Info("Connecting to db...");

                _manager = new MailBoxManager(25, _log);

                var auth_error_warning_timeout =
                    ConfigurationManager.AppSettings["mail.AuthErrorSendWarningAlertTimeout"] != null
                        ? TimeSpan.FromSeconds(
                            Convert.ToInt32(ConfigurationManager.AppSettings["mail.AuthErrorSendWarningAlertTimeout"]))
                        : TimeSpan.FromHours(2);

                _manager.AuthErrorWarningTimeout = auth_error_warning_timeout;

                _log.Info("Auth login error warning timeout is {0}.", auth_error_warning_timeout.ToString());

                var auth_error_disable_mailbox_timeout =
                    ConfigurationManager.AppSettings["mail.AuthErrorDisableMailboxTimeout"] != null
                        ? TimeSpan.FromSeconds(
                            Convert.ToInt32(ConfigurationManager.AppSettings["mail.AuthErrorDisableMailboxTimeout"]))
                        : TimeSpan.FromDays(3);

                _log.Info("Auth login error disable mailbox timeout is {0}.", auth_error_disable_mailbox_timeout.ToString());

                _manager.AuthErrorDisableTimeout = auth_error_disable_mailbox_timeout;

                _log.Info("Creating collector service...");

                var handlers_log = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Nlog, "MessageHandlers");
                var queue_settings = MailQueueSettings.FromConfig;
                if (work_on_this_users_only != null)
                    queue_settings.WorkOnUsersOnly = work_on_this_users_only.ToList();
                else
                {
                    var user_to_work_on = ConfigurationManager.AppSettings["mail.OneUserMode"];
                    if (!string.IsNullOrEmpty(user_to_work_on))
                        queue_settings.WorkOnUsersOnly.Add(user_to_work_on);
                }

                _manager.TenantOverdueDays = queue_settings.OverdueDays;

                var handlers = MessageHandlersSettings.FromConfig(handlers_log, "mail");

                var enable_activity_log = ConfigurationManager.AppSettings["mail.EnableActivityLog"] == null || Convert.ToBoolean(ConfigurationManager.AppSettings["mail.EnableActivityLog"]);

                _manager.EnableActivityLog = enable_activity_log;

                _log.Info("Db aggregator activity log is {0}.", enable_activity_log ? "enabled" : "disabled");

                _collector = new Collector(_manager, queue_settings, handlers);

                _log.Info("Service is ready.");

                AggregatorLogger.Instance.Initialize(_manager, GetServiceIp());
                _log.Info("Aggregator logger initialized.");
            }
            catch (Exception ex)
            {
                _log.Fatal("CollectorService error under constuct: {0}", ex.ToString());
            }
        }
Exemple #45
0
        public MailAccountData CreateAccountSimple(string email, string password)
        {
            if (string.IsNullOrEmpty(email))
            {
                throw new ArgumentException(@"Empty email", "email");
            }

            Thread.CurrentThread.CurrentCulture   = CurrentCulture;
            Thread.CurrentThread.CurrentUICulture = CurrentCulture;

            string  errorText = null;
            MailBox mbox      = null;

            var domain = email.Substring(email.IndexOf('@') + 1);

            var mailboxSettings = MailBoxManager.GetMailBoxSettings(domain);

            if (mailboxSettings == null)
            {
                errorText = GetFormattedTextError(new ItemNotFoundException("Unknown mail provider settings."));
            }
            else
            {
                try
                {
                    var testMailboxes = mailboxSettings.ToMailboxList(email, password, TenantId, Username);

                    var results = new List <LoginResult>();

                    foreach (var mb in testMailboxes)
                    {
                        LoginResult loginResult;

                        using (var client = new MailClient(mb, CancellationToken.None, 5000, SslCertificatesErrorPermit, log: _log))
                        {
                            loginResult = client.TestLogin();
                        }

                        results.Add(loginResult);

                        if (loginResult.IngoingSuccess && loginResult.OutgoingSuccess)
                        {
                            mbox = mb;
                            break;
                        }
                    }

                    if (mbox == null)
                    {
                        var i = 0;

                        foreach (var loginResult in results)
                        {
                            errorText += string.Format("#{0}:<br>", ++i);

                            if (!loginResult.IngoingSuccess)
                            {
                                errorText += GetFormattedTextError(loginResult.IngoingException,
                                                                   loginResult.Imap ? MailServerType.Imap : MailServerType.Pop3, false) + "<br>";
                                // exImap is ImapConnectionTimeoutException
                            }

                            if (!loginResult.OutgoingSuccess)
                            {
                                errorText += GetFormattedTextError(loginResult.OutgoingException, MailServerType.Smtp, false) + "<br>";
                                // exSmtp is SmtpConnectionTimeoutException);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    errorText = GetFormattedTextError(ex);
                }
            }

            if (!string.IsNullOrEmpty(errorText))
            {
                throw new Exception(errorText);
            }

            try
            {
                MailBoxManager.SaveMailBox(mbox);
                MailBoxManager.CachedAccounts.Clear(Username);

                if (IsSignalRAvailable)
                {
                    MailBoxManager.UpdateUserActivity(TenantId, Username);
                }

                var account = new AccountInfo(mbox.MailBoxId, mbox.EMailView, mbox.Name, mbox.Enabled, mbox.QuotaError,
                                              MailBox.AuthProblemType.NoProblems, new MailSignature(mbox.MailBoxId, TenantId, "", false),
                                              new MailAutoreply(mbox.MailBoxId, TenantId, false, false, false, DateTime.MinValue,
                                                                DateTime.MinValue, String.Empty, String.Empty), false, mbox.EMailInFolder, false, false);

                return(account.ToAddressData().FirstOrDefault());
            }
            catch (Exception ex)
            {
                //TODO: change AttachmentsUnknownError to common unknown error text
                errorText = GetFormattedTextError(ex, MailApiResource.AttachmentsUnknownError);
            }

            throw new Exception(errorText);
        }
Exemple #46
0
        public MailAccountData UpdateAccountOAuth(string code, byte type, int mailboxId)
        {
            if (string.IsNullOrEmpty(code))
            {
                throw new ArgumentException(@"Empty oauth code", "code");
            }

            var oAuthToken = OAuth20TokenHelper.GetAccessToken(GoogleLoginProvider.GoogleOauthTokenUrl,
                                                               GoogleLoginProvider.GoogleOAuth20ClientId,
                                                               GoogleLoginProvider.GoogleOAuth20ClientSecret,
                                                               GoogleLoginProvider.GoogleOAuth20RedirectUrl,
                                                               code);

            if (oAuthToken == null)
            {
                throw new Exception(@"Empty oauth token");
            }

            var loginProfile = new GoogleLoginProvider().GetLoginProfile(oAuthToken.AccessToken);
            var email        = loginProfile.EMail;

            if (string.IsNullOrEmpty(email))
            {
                throw new Exception(@"Empty email");
            }

            try
            {
                var mbox = MailBoxManager.GetMailBox(mailboxId);

                if (null == mbox)
                {
                    throw new ArgumentException("Mailbox with specified email doesn't exist.");
                }

                if (mbox.IsTeamlab || !mbox.IsOAuth)
                {
                    throw new ArgumentException("Mailbox with specified email can't be updated");
                }

                if (!mbox.EMail.Address.Equals(email, StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new ArgumentException("Mailbox with specified email can't be updated");
                }

                mbox.OAuthToken           = oAuthToken.ToJson();
                mbox.AccessTokenRefreshed = true;

                MailBoxManager.SaveMailBox(mbox, (AuthorizationServiceType)type);
                MailBoxManager.CachedAccounts.Clear(Username);

                if (IsSignalRAvailable)
                {
                    MailBoxManager.UpdateUserActivity(TenantId, Username);
                }

                var accountInfo = new AccountInfo(mbox.MailBoxId, mbox.EMailView, mbox.Name, mbox.Enabled, mbox.QuotaError,
                                                  MailBox.AuthProblemType.NoProblems, new MailSignature(mbox.MailBoxId, TenantId, "", false),
                                                  new MailAutoreply(mbox.MailBoxId, TenantId, false, false, false, DateTime.MinValue,
                                                                    DateTime.MinValue, String.Empty, String.Empty), false, mbox.EMailInFolder, false, false);

                return(accountInfo.ToAddressData().FirstOrDefault());
            }
            catch (Exception imapException)
            {
                throw new Exception(GetFormattedTextError(imapException, MailServerType.ImapOAuth, imapException is ImapConnectionTimeoutException));
            }
        }
Exemple #47
0
 public void Setup()
 {
     _mailBoxManager = new MailBoxManager(30);
 }
Exemple #48
0
        public static MailMessage Save(MailBox mailbox, MimeMessage mimeMessage, string uid, MailFolder folder, bool unread = true, ILogger log = null)
        {
            if (mailbox == null)
            {
                throw new ArgumentException("mailbox is null", "mailbox");
            }

            if (mimeMessage == null)
            {
                throw new ArgumentException("message is null", "mimeMessage");
            }

            if (uid == null)
            {
                throw new ArgumentException("uidl is null", "uid");
            }

            if (log == null)
            {
                log = new NullLogger();
            }

            var manager = new MailBoxManager(log);

            var fromEmail = mimeMessage.From.Mailboxes.FirstOrDefault();

            var md5 =
                string.Format("{0}|{1}|{2}|{3}",
                              mimeMessage.From.Mailboxes.Any() ? mimeMessage.From.Mailboxes.First().Address : "",
                              mimeMessage.Subject, mimeMessage.Date.UtcDateTime, mimeMessage.MessageId).GetMd5();

            var uidl = mailbox.Imap ? string.Format("{0}-{1}", uid, folder.FolderId) : uid;

            var fromThisMailBox = fromEmail != null &&
                                  fromEmail.Address.ToLowerInvariant()
                                  .Equals(mailbox.EMail.Address.ToLowerInvariant());

            var toThisMailBox =
                mimeMessage.To.Mailboxes.Select(addr => addr.Address.ToLowerInvariant())
                .Contains(mailbox.EMail.Address.ToLowerInvariant());

            List <int> tagsIds = null;

            if (folder.Tags.Any())
            {
                log.Debug("GetOrCreateTags()");

                tagsIds = manager.GetOrCreateTags(mailbox.TenantId, mailbox.UserId, folder.Tags);
            }

            log.Debug("SearchExistingMessagesAndUpdateIfNeeded()");

            var found = manager.SearchExistingMessagesAndUpdateIfNeeded(mailbox, folder.FolderId, uidl, md5,
                                                                        mimeMessage.MessageId, fromThisMailBox, toThisMailBox, tagsIds);

            var needSave = !found;

            if (!needSave)
            {
                return(null);
            }

            log.Debug("DetectChainId()");

            var chainId = manager.DetectChainId(mailbox, mimeMessage.MessageId, mimeMessage.InReplyTo,
                                                mimeMessage.Subject);

            var streamId = MailUtil.CreateStreamId();

            log.Debug("Convert MimeMessage->MailMessage");

            var message = ConvertToMailMessage(mimeMessage, folder, unread, chainId, streamId, log);

            log.Debug("TryStoreMailData()");

            if (!TryStoreMailData(message, mailbox, log))
            {
                return(null);
            }

            log.Debug("MailSave()");

            if (TrySaveMail(manager, mailbox, message, folder, uidl, md5, log))
            {
                return(message);
            }

            if (manager.TryRemoveMailDirectory(mailbox, message.StreamId))
            {
                log.Info("Problem with mail proccessing(Account:{0}). Body and attachment have been deleted", mailbox.EMail);
            }
            else
            {
                throw new Exception("Can't delete mail folder with data");
            }

            return(null);
        }
 public void Setup()
 {
     mailBoxManager = new MailBoxManager(ConfigurationManager.ConnectionStrings["mail"], 30);
 }