Exemple #1
0
 protected void DisplayStandardMode()
 {
     switcherHref    = "?mode=advanced";
     switcherText    = _resMan.GetString("AdvancedLogin");
     advancedDisplay = @"none";
     advancedLogin   = "******";
     if (settings.HideLoginMode == LoginMode.HideEmailField ||
         settings.HideLoginMode == LoginMode.HideEmailFieldDisplayDomainAfterLogin ||
         settings.HideLoginMode == LoginMode.HideEmailFieldDisplayDomainAfterLoginAndLoginIsLoginAndDomain ||
         settings.HideLoginMode == LoginMode.HideEmailFieldLoginIsLoginAndDomain)
     {
         emailClass    = @" class=""wm_hide""";
         emailTabIndex = "-1";
     }
     if (settings.HideLoginMode == LoginMode.HideLoginFieldLoginIsAccount ||
         settings.HideLoginMode == LoginMode.HideLoginFieldLoginIsEmail)
     {
         loginClass    = @" class=""wm_hide""";
         loginTabIndex = "-1";
     }
     if (settings.HideLoginMode == LoginMode.HideEmailFieldDisplayDomainAfterLogin ||
         settings.HideLoginMode == LoginMode.HideEmailFieldDisplayDomainAfterLoginAndLoginIsLoginAndDomain)
     {
         loginWidth    = "150px";
         domainContent = " @" + defaultDomainOptional;
     }
 }
Exemple #2
0
        public void Save()
        {
            WebmailResourceManager _resMan = (new WebmailResourceManagerCreator()).CreateResourceManager();

            _flagsStr = Utils.SystemMessageFlagsToStr(_flags);
            string FullOldFileName = Path.Combine(_folderFullPath, _fileName);
            string NewFileName;

            if (_flagsStr.Trim() != string.Empty)
            {
                NewFileName = _uid + Constants.SIZE_DELIMETER + _size + Constants.FLAG_DELIMETER + _flagsStr;
            }
            else
            {
                NewFileName = _uid + Constants.SIZE_DELIMETER + _size + Constants.FLAG_DELIMETER;
            }
            string FullFileName = Path.Combine(_folderFullPath, NewFileName);

            if (File.Exists(FullOldFileName))
            {
                File.Move(FullOldFileName, FullFileName);
            }
            else
            {
                throw new WebMailWMServerException(_resMan.GetString("PROC_MSG_HAS_DELETED"));
            }
        }
Exemple #3
0
        protected void LoadByUid(string uid)
        {
            WebmailResourceManager _resMan = (new WebmailResourceManagerCreator()).CreateResourceManager();

            _uid = uid;
            if (Directory.Exists(_folderFullPath))
            {
                DirectoryInfo dir   = new DirectoryInfo(_folderFullPath);
                FileInfo[]    files = dir.GetFiles(uid + "*");
                foreach (FileInfo file in files)
                {
                    string tuid = GetUIDByFileName(file.Name);
                    if (tuid == uid)
                    {
                        _fileName = file.Name;
                        _flagsStr = GetFlagsByFileName(file.Name);
                        _size     = GetSizeByFileName(file.Name);
                        _flags    = Utils.StrToSystemMessageFlags(_flagsStr);
                        break;
                    }
                }
            }
            else
            {
                throw new WebMailWMServerException(_resMan.GetString("PROC_MSG_HAS_DELETED"));
            }
        }
Exemple #4
0
        public static User CreateUser()
        {
            WebmailResourceManager resMan = (new WebmailResourceManagerCreator()).CreateResourceManager();
            User             newUser      = null;
            DbManagerCreator creator      = new DbManagerCreator();
            DbManager        dbMan        = creator.CreateDbManager();

            try
            {
                dbMan.Connect();

                WebmailSettings settings = (new WebMailSettingsCreator()).CreateWebMailSettings();

                int  LicensesNum = Utils.GetLicensesNum(settings.LicenseKey);
                int  Users       = dbMan.GetUsersCountNotDel();
                bool Deleted     = ((LicensesNum > 0) && (Users >= LicensesNum)) ? true : false;
                if (!Deleted)
                {
                    newUser = dbMan.CreateUser(Deleted);
                }
                else
                {
                    throw new WebMailException(resMan.GetString("ErrorMaximumUsersLicenseIsExceeded"));
                }
            }
            finally
            {
                dbMan.Disconnect();
            }
            return(newUser);
        }
Exemple #5
0
        public void CreateAccount()
        {
            WebmailResourceManager resMan = (new WebmailResourceManagerCreator()).CreateResourceManager();

            if (!IsFolderNameValid(_accountName))
            {
                throw new WebMailIOException(resMan.GetString("CantCreateAccount"));
            }

            CreateFolder("");
        }
Exemple #6
0
        public override void Connect()
        {
            System.Threading.Thread.Sleep(50);
            WebmailResourceManager resMan = (new WebmailResourceManagerCreator()).CreateResourceManager();

            try
            {
                _pop3Obj.InboxPreloadOptions = Pop3InboxPreloadOptions.Uidl;
                if (_account.MailIncomingPort == 995)
                {
                    _pop3Obj.SslMode     = SslStartupMode.OnConnect;
                    _pop3Obj.SslProtocol = SecurityProtocol.Auto;
                    _pop3Obj.SslCertificates.AutoValidation = CertificateValidationFlags.None;
                }
                Log.WriteLine("POP3 Connect", string.Format(@"'{0}' - '{1}'", _account.MailIncomingHost, _account.MailIncomingPort));
                Log.WriteLine("POP3 Connect", string.Format(@"IsConnected - '{0}'", _pop3Obj.IsConnected));
                _pop3Obj.Connect(_account.MailIncomingHost, _account.MailIncomingPort, true);
                Log.WriteLine("POP3 Connect", string.Format(@"IsConnected - '{0}'", _pop3Obj.IsConnected));
                Log.WriteLine("POP3 Login", string.Format(@"'{0}' - '{1}'", _account.MailIncomingLogin, _account.MailIncomingPassword));
                Log.WriteLine("POP3 Login", string.Format(@"IsLogined - '{0}'", _pop3Obj.IsLoggedIn));
                _pop3Obj.Login(_account.MailIncomingLogin, _account.MailIncomingPassword, AuthenticationMethods.Auto, AuthenticationOptions.PreferSimpleMethods, null);
                Log.WriteLine("POP3 Login", string.Format(@"IsLogined - '{0}'", _pop3Obj.IsLoggedIn));
            }
            catch (MailBeeConnectionException ex)
            {
                Log.WriteException(ex);
                throw new WebMailException(resMan.GetString("ErrorPOP3Connect"));
            }
            catch (MailBeePop3LoginBadCredentialsException ex)
            {
                Log.WriteException(ex);
                throw new WebMailException(resMan.GetString("ErrorPOP3IMAP4Auth"));
            }
            catch (MailBeeException ex)
            {
                Log.WriteException(ex);
                throw new WebMailMailBeeException(ex);
            }
        }
Exemple #7
0
        public void RenameAccount(string newName)
        {
            WebmailResourceManager resMan = (new WebmailResourceManagerCreator()).CreateResourceManager();

            if (!IsFolderNameValid(_accountName))
            {
                throw new WebMailIOException(resMan.GetString("PROC_CANT_UPDATE_ACCT"));
            }

            try
            {
                string sourceDirName = CreateFolderFullPath("");
                _accountName = newName;
                string destDirName = CreateFolderFullPath("");
                if (Directory.Exists(sourceDirName))
                {
                    string rootDir = Path.GetDirectoryName(destDirName);
                    Directory.CreateDirectory(rootDir);
                    Directory.Move(sourceDirName, destDirName);
                }
                else
                {
                    throw new DirectoryNotFoundException();
                }
            }
            catch (ArgumentException ex)
            {
                Log.WriteException(ex);
                throw new WebMailIOException(ex);
            }
            catch (IOException ex)
            {
                Log.WriteException(ex);
                throw new WebMailIOException(ex);
            }
            catch (UnauthorizedAccessException ex)
            {
                Log.WriteException(ex);
                throw new WebMailIOException(ex);
            }
        }
Exemple #8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Account acct = Session[Constants.sessionAccount] as Account;

            if (acct != null)
            {
                int fileType             = (string.Compare(Request.Form["file_type"], "0", true, CultureInfo.InvariantCulture) == 0) ? 0 : 1;
                HttpFileCollection files = Request.Files;
                if ((files != null) && (files.Count > 0))
                {
                    HttpPostedFile file = files[0];
                    if (file != null)
                    {
                        byte[] buffer = null;
                        using (Stream uploadStream = file.InputStream)
                        {
                            buffer = new byte[uploadStream.Length];
                            long numBytesToRead = uploadStream.Length;
                            long numBytesRead   = 0;
                            while (numBytesToRead > 0)
                            {
                                int n = uploadStream.Read(buffer, (int)numBytesRead, (int)numBytesToRead);
                                if (n == 0)
                                {
                                    break;
                                }
                                numBytesRead   += n;
                                numBytesToRead -= n;
                            }
                        }
                        if (buffer != null)
                        {
                            try
                            {
                                string    csvText = Encoding.Default.GetString(buffer);
                                CsvParser parser  = new CsvParser(csvText, true);
                                DataTable dt      = parser.Parse();
                                if (dt.Rows.Count == 0)
                                {
                                    WebmailResourceManager resMan = (new WebmailResourceManagerCreator()).CreateResourceManager();
                                    Log.WriteLine("import Page_Load", "Error: No contacts for import");
                                    _jsErrorCode        = 2;
                                    _jsContactsImported = 0;
                                    Session[Constants.sessionReportText] = string.Format(@"{0}", resMan.GetString("ErrorNoContacts"));
                                    return;
                                }

                                ArrayList contacts = new ArrayList();
                                for (int rowsIndex = 0; rowsIndex < dt.Rows.Count; rowsIndex++)
                                {
                                    bool contactInitialized    = false;
                                    AddressBookContact contact = new AddressBookContact();
                                    contact.IDUser = acct.UserOfAccount.ID;
                                    string  firstName   = string.Empty;
                                    string  lastName    = string.Empty;
                                    string  nickname    = string.Empty;
                                    string  displayName = string.Empty;
                                    string  birthday    = string.Empty;
                                    DataRow dr          = dt.Rows[rowsIndex];
                                    for (int columnsIndex = 0; columnsIndex < dt.Columns.Count; columnsIndex++)
                                    {
                                        if (dr[columnsIndex] != DBNull.Value)
                                        {
                                            if (dr[columnsIndex] as string != null)
                                            {
                                                switch (dt.Columns[columnsIndex].ColumnName.ToLower())
                                                {
                                                case "first name":
                                                case "firstname":
                                                    firstName          = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "last name":
                                                case "lastname":
                                                    lastName           = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "notes":
                                                    contact.Notes      = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "home street":
                                                case "homestreet":
                                                case "homeaddress":
                                                    contact.HStreet    = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "home city":
                                                case "homecity":
                                                    contact.HCity      = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "home postal code":
                                                case "zip":
                                                    contact.HZip       = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "home state":
                                                case "homestate":
                                                    contact.HState     = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "home country":
                                                case "homecountry":
                                                case "home country/region":
                                                    contact.HCountry   = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "home phone":
                                                case "homephone":
                                                    contact.HPhone     = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "home fax":
                                                case "homefax":
                                                    contact.HFax       = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "mobile phone":
                                                case "mobilephone":
                                                    contact.HMobile    = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "web page":
                                                case "webpage":
                                                case "personal web page":
                                                case "personalwebpage":
                                                    contact.HWeb       = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "company":
                                                    contact.BCompany   = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "business street":
                                                case "businessstreet":
                                                    contact.BStreet    = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "business city":
                                                case "businesscity":
                                                    contact.BCity      = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "business state":
                                                case "businessstate":
                                                    contact.BState     = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "business postal code":
                                                    contact.BZip       = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "business country":
                                                case "business country/region":
                                                    contact.BCountry   = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "job title":
                                                case "jobtitle":
                                                    contact.BJobTitle  = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "department":
                                                    contact.BDepartment = dr[columnsIndex] as string;
                                                    contactInitialized  = true;
                                                    break;

                                                case "office location":
                                                case "officelocation":
                                                    contact.BOffice    = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "business phone":
                                                case "businessphone":
                                                    contact.BOffice    = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "business fax":
                                                case "businessfax":
                                                    contact.BFax       = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "business web page":
                                                case "businesswebpage":
                                                    contact.BWeb       = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "e-mail address":
                                                case "e-mailaddress":
                                                case "emailaddress":
                                                case "e-mail":
                                                case "email":
                                                    contact.HEmail     = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "e-mail display name":
                                                case "e-maildisplayname":
                                                case "emaildisplayname":
                                                case "name":
                                                    displayName        = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "birthday":
                                                    birthday           = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;

                                                case "nickname":
                                                    nickname           = dr[columnsIndex] as string;
                                                    contactInitialized = true;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    if (!contactInitialized)
                                    {
                                        WebmailResourceManager resMan = (new WebmailResourceManagerCreator()).CreateResourceManager();
                                        Log.WriteLine("import Page_Load", "Error: CSV file has invalid format");
                                        _jsErrorCode        = 3;
                                        _jsContactsImported = 0;
                                        Session[Constants.sessionReportText] = string.Format(@"{0}", resMan.GetString("ErrorInvalidCSV"));
                                        break;
                                    }
                                    string fullName;
                                    if (nickname != string.Empty)
                                    {
                                        fullName = string.Format("{0} \"{1}\" {2}", firstName, nickname, lastName);
                                    }
                                    else
                                    {
                                        fullName = string.Format("{0} {1}", firstName, lastName);
                                    }
                                    contact.FullName = fullName;
                                    try
                                    {
                                        DateTime birthdayDate = DateTime.Parse(birthday);
                                        contact.BirthdayDay   = (byte)birthdayDate.Day;
                                        contact.BirthdayMonth = (byte)birthdayDate.Month;
                                        contact.BirthdayYear  = (short)birthdayDate.Year;
                                    }
                                    catch {}
                                    contacts.Add(contact);
                                }
                                DbStorage storage = DbStorageCreator.CreateDatabaseStorage(acct);
                                try
                                {
                                    storage.Connect();
                                    foreach (AddressBookContact contact in contacts)
                                    {
                                        contact.AutoCreate = true;

                                        try
                                        {
                                            storage.CreateAddressBookContact(contact);
                                            _jsContactsImported++;
                                        }
                                        catch { }
                                    }
                                    _jsErrorCode = 1;
                                    WebmailResourceManager resMan = (new WebmailResourceManagerCreator()).CreateResourceManager();
                                    Session[Constants.sessionReportText] = string.Format(@"{0} {1} {2}", resMan.GetString("InfoHaveImported"), _jsContactsImported, resMan.GetString("InfoNewContacts"));
                                }
                                finally
                                {
                                    storage.Disconnect();
                                }
                            }
                            catch
                            {
                                Log.WriteLine("import Page_Load", "Error while importing contacts");
                                _jsErrorCode        = 0;
                                _jsContactsImported = 0;
                            }
                        }
                    }
                }
            }
        }
Exemple #9
0
        public static Account LoginAccount(string email, string login, string password, string incomingMailServer,
                                           IncomingMailProtocol incomingMailProtocol, int incomingPort, string outgoingMailServer,
                                           int outgoingMailPort, bool useSmtpAuthentication, bool signAutomatically, bool advanced_login,
                                           string language)
        {
            WebmailSettings settings  = (new WebMailSettingsCreator()).CreateWebMailSettings();
            string          tempLogin = login;

            if (!advanced_login)
            {
                switch (settings.HideLoginMode)
                {
                case LoginMode.HideLoginFieldLoginIsAccount:
                    login     = EmailAddress.Parse(email).GetAccountName();
                    tempLogin = null;
                    break;

                case LoginMode.HideLoginFieldLoginIsEmail:
                    login     = email;
                    tempLogin = null;
                    break;

                case LoginMode.HideEmailField:
                case LoginMode.HideEmailFieldDisplayDomainAfterLogin:
                    email = string.Format("{0}@{1}", login, settings.DefaultDomainOptional);
                    break;

                case LoginMode.HideEmailFieldLoginIsLoginAndDomain:
                case LoginMode.HideEmailFieldDisplayDomainAfterLoginAndLoginIsLoginAndDomain:
                    email     = string.Format("{0}@{1}", login, settings.DefaultDomainOptional);
                    login     = email;
                    tempLogin = email;
                    break;
                }
            }

            WebmailResourceManager resMan = (new WebmailResourceManagerCreator()).CreateResourceManager();

            string domainName = EmailAddress.GetDomainFromEmail(email);
            Domain domain     = LoadDomainFromDb(domainName);

/*
 *                      if (domain != null && (domain.MailIncomingProtocol == IncomingMailProtocol.WMServer ||
 *                              incomingMailProtocol == IncomingMailProtocol.WMServer) && settings.EnableWmServer)
 *                      {
 *                              tempLogin = EmailAddress.GetAccountNameFromEmail(tempLogin);
 *                              if (tempLogin != null && tempLogin != EmailAddress.GetAccountNameFromEmail(email))
 *                              {
 *                                      throw new WebMailException(resMan.GetString("ErrorPOP3IMAP4Auth"));
 *                              }
 *                      }
 */
            Account result = LoadFromDb(email, tempLogin, null);

            if (result == null)
            {
                if (!settings.AllowNewUsersRegister)
                {
                    throw new WebMailException(resMan.GetString("ErrorPOP3IMAP4Auth"));
                }
                if (domain != null)
                {
                    if (settings.AllowNewUsersRegister && domain.MailIncomingProtocol == IncomingMailProtocol.WMServer)
                    {
                        throw new WebMailException(resMan.GetString("ErrorPOP3IMAP4Auth"));
                    }
                }

                Account acct = new Account();
                if (domain != null && (domain.MailIncomingProtocol != IncomingMailProtocol.WMServer || settings.EnableWmServer))
                {
                    acct.Email = email;
                    if (domain.MailIncomingProtocol == IncomingMailProtocol.WMServer)
                    {
                        acct.MailIncomingLogin = EmailAddress.GetAccountNameFromEmail(email);
                    }
                    else
                    {
                        acct.MailIncomingLogin = login;
                    }
                    acct.MailIncomingPassword       = password;
                    acct.MailIncomingHost           = domain.MailIncomingHost;
                    acct.MailIncomingPort           = domain.MailIncomingPort;
                    acct.MailIncomingProtocol       = domain.MailIncomingProtocol;
                    acct.MailOutgoingHost           = domain.MailOutgoingHost;
                    acct.MailOutgoingPort           = domain.MailOutgoingPort;
                    acct.MailOutgoingAuthentication = domain.MailOutgoingAuthentication;
                    acct.IDDomain = domain.ID;
                }
                else
                {
                    acct.Email                      = email;
                    acct.MailIncomingLogin          = login;
                    acct.MailIncomingPassword       = password;
                    acct.MailIncomingHost           = incomingMailServer;
                    acct.MailIncomingPort           = incomingPort;
                    acct.MailIncomingProtocol       = incomingMailProtocol;
                    acct.MailOutgoingHost           = outgoingMailServer;
                    acct.MailOutgoingPort           = outgoingMailPort;
                    acct.MailOutgoingAuthentication = useSmtpAuthentication;
                    acct.IDDomain                   = 0;
                }

                bool isWmServer = (acct.MailIncomingProtocol == IncomingMailProtocol.WMServer);
                bool isIMAP4    = (acct.MailIncomingProtocol == IncomingMailProtocol.Imap4);
                if (!isWmServer)
                {
                    MailServerStorage mss = MailServerStorageCreator.CreateMailServerStorage(acct);
                    try
                    {
                        mss.Connect();
                    }
                    finally
                    {
                        if (mss.IsConnected())
                        {
                            mss.Disconnect();
                        }
                    }
                }
                User usr = null;
                try
                {
                    usr = User.CreateUser();
                    FolderSyncType syncType = Folder.DefaultInboxSyncType;
                    if (settings.DirectModeIsDefault)
                    {
                        syncType = FolderSyncType.DirectMode;
                    }
                    if (isWmServer)
                    {
                        syncType = FolderSyncType.AllHeadersOnly;
                    }
                    if (isIMAP4)
                    {
                        syncType = FolderSyncType.DirectMode;
                    }

                    result = usr.CreateAccount(acct, syncType, advanced_login);
                }
                catch (WebMailException)
                {
                    if (null != usr)
                    {
                        User.DeleteUserSettings(usr.ID);
                    }
                    throw;
                }
            }
            else
            {
                if (result.UserOfAccount.Deleted)
                {
                    throw new WebMailException((new WebmailResourceManagerCreator()).CreateResourceManager().GetString("ErrorMaximumUsersLicenseIsExceeded"));
                }

                if (result.Deleted)
                {
                    throw new WebMailException("Your account is inactive, please contact the system administrator on this.");
                }

                if (string.Compare(result.MailIncomingPassword, password, false, CultureInfo.InvariantCulture) != 0)
                {
                    result.MailIncomingPassword = password;
                    MailServerStorage mss = MailServerStorageCreator.CreateMailServerStorage(result);
                    try
                    {
                        mss.Connect();
                    }
                    finally
                    {
                        if (mss.IsConnected())
                        {
                            mss.Disconnect();
                        }
                    }
                }

                if (result.DefaultAccount == false)
                {
                    DbManagerCreator creator = new DbManagerCreator();
                    DbManager        dbMan   = creator.CreateDbManager();
                    int nonDefaultCount;
                    try
                    {
                        dbMan.Connect();
                        nonDefaultCount = dbMan.GetNotDefaultAccountCount(email, login, password);
                    }
                    finally
                    {
                        dbMan.Disconnect();
                    }
                    if (nonDefaultCount > 1)
                    {
                        throw new WebMailException((new WebmailResourceManagerCreator()).CreateResourceManager().GetString("PROC_CANT_LOG_NONDEF"));
                    }
                }
            }
            if ((result != null) && (result.UserOfAccount != null) && (result.UserOfAccount.Settings != null))
            {
                result.UserOfAccount.Settings.LastLogin = DateTime.Now;
                result.UserOfAccount.Settings.LoginsCount++;
                if (!string.IsNullOrEmpty(language) && settings.AllowLanguageOnLogin)
                {
                    result.UserOfAccount.Settings.DefaultLanguage = language;
                }

                if (result.MailIncomingProtocol == IncomingMailProtocol.Imap4)
                {
                    ImapStorage imapStorage = new ImapStorage(result);
                    try
                    {
                        imapStorage.Connect();
                        result.Namespace = imapStorage.GetNamespace();

                        if (settings.TakeImapQuota)
                        {
                            if (imapStorage.IsQuotaSupported())
                            {
                                if (result.Imap_quota != 0)
                                {
                                    result.Imap_quota = 1;
                                    result.UserOfAccount.Settings.MailboxLimit = imapStorage.GetMailStorageSize();
                                }
                            }
                            else
                            {
                                result.Imap_quota = -1;
                            }
                        }
                    }
                    finally
                    {
                        imapStorage.Disconnect();
                    }
                }

                result.Update(true);
            }

            // Create Trash Folder if Trash not found in the list
            if (result != null && result.MailIncomingProtocol == IncomingMailProtocol.WMServer)
            {
                MailServerStorage wmServerStorage = MailServerStorageCreator.CreateMailServerStorage(result);

                try
                {
                    wmServerStorage.Connect();
                    FolderCollection fc = wmServerStorage.GetFolders();

                    FileSystem fs  = new FileSystem(result.Email, result.ID, true);
                    Folder     fld = fc[FolderType.Trash];
                    if (fld == null)
                    {
                        string       fullPath = result.Delimiter + Constants.FolderNames.Trash;
                        const string name     = Constants.FolderNames.Trash;
                        if (!settings.StoreMailsInDb)
                        {
                            fs.CreateFolder(Constants.FolderNames.Trash);
                        }
                        fld = new Folder(result.ID, -1, fullPath, name);
                        wmServerStorage.CreateFolder(fld);

                        DbManagerCreator creator = new DbManagerCreator();
                        DbManager        dbMan   = creator.CreateDbManager();
                        try
                        {
                            dbMan.Connect();
                            dbMan.CreateFolder(result.ID, -1, FolderType.Trash, name, fullPath, FolderSyncType.AllHeadersOnly, false, 3);
                        }
                        finally
                        {
                            dbMan.Disconnect();
                        }
                    }
                }
                catch { }
            }

            return(result);
        }
 protected void CheckMailForAccount(Account acct)
 {
     if (acct != null)
     {
         try
         {
             DbStorage              dbs     = DbStorageCreator.CreateDatabaseStorage(acct);
             MailProcessor          mp      = new MailProcessor(dbs);
             WebmailResourceManager _resMan = (new WebmailResourceManagerCreator()).CreateResourceManager();
             try
             {
                 mp.MessageDownloaded += new DownloadedMessageHandler(mp_MessageDownloaded);
                 Response.Write(@"<script type=""text/javascript"">parent.SetStateTextHandler(""" + _resMan.GetString("LoggingToServer") + @""");</script>");
                 mp.Connect();
                 Response.Write(@"<script type=""text/javascript"">parent.SetStateTextHandler(""" + _resMan.GetString("GettingMsgsNum") + @""");</script>");
                 Dictionary <long, string> updatedFolders = mp.Synchronize(dbs.GetFolders());
                 if (Type == 0)
                 {
                     string strFolders = "";
                     foreach (KeyValuePair <long, string> kvp in updatedFolders)
                     {
                         strFolders += "{id: " + kvp.Key.ToString() + ", fullName: '" + kvp.Value + "'}, ";
                     }
                     Response.Write(@"<script type=""text/javascript"">parent.SetUpdatedFolders([" + strFolders.TrimEnd(new char[2] {
                         ',', ' '
                     }) + "]);</script>");
                 }
             }
             finally
             {
                 mp.MessageDownloaded -= new DownloadedMessageHandler(mp_MessageDownloaded);
                 Response.Write(@"<script type=""text/javascript"">parent.SetStateTextHandler(""" + _resMan.GetString("LoggingOffFromServer") + @""");</script>");
                 mp.Disconnect();
             }
         }
         catch (WebMailException ex)
         {
             Log.WriteException(ex);
             errorDesc = Utils.EncodeJsSaveString(ex.Message);
             if (Type == 1)
             {
                 Session.Add(Constants.sessionErrorText, errorDesc);
             }
         }
     }
 }
Exemple #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (File.Exists(Path.Combine(MapPath(""), "VERSION")))
            {
                _WmVersion = File.ReadAllText(Path.Combine(MapPath(""), "VERSION"));
            }

            if (!IsPostBack)
            {
                Log.Write("WebMail Version: " + _WmVersion + "\r\n");
                this.Context.Application.Remove(Constants.sessionSettings);
                if (Request.QueryString.Get("mode") != null)
                {
                    mode = Request.QueryString.Get("mode");
                }
                if (mode == "logout")
                {
                    Log.WriteLine("Page_Load", "Session Clear");
                    Session.Clear();
                }
                if (Application[Constants.appSettingsDataFolderPath] == null)
                {
                    Application[Constants.appSettingsDataFolderPath] = ConfigurationManager.AppSettings[Constants.appSettingsDataFolderPath];
                }
                Session.Remove(Constants.sessionAccount);
            }
            Dictionary <string, string> supportedLangs = new Dictionary <string, string>();

            try
            {
                settings       = (new WebMailSettingsCreator()).CreateWebMailSettings(Utils.GetDataFolderPath(), Request.Url.Host);
                supportedLangs = Utils.GetSupportedLangs();
                if (settings.AllowLanguageOnLogin)
                {
                    foreach (KeyValuePair <string, string> kvp in supportedLangs)
                    {
                        _languageOptions += @"<a href=""#"" name=""lng_" + kvp.Key + @""" onclick=""ChangeLang(this); return false;"">" + kvp.Value + @"</a>";
                    }
                    _languageClassName = "";
                }
            }
            catch (WebMailDatabaseException)
            {
            }
            catch (WebMailSettingsException)
            {
                Response.Write(@"
<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"" />
<html>
<head>
    <meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"" />
	<link rel=""shortcut icon"" href=""favicon.ico"" />
    <meta http-equiv=""Content-Script-Type"" content=""text/javascript"" />
    <meta http-equiv=""Cache-Control"" content=""private,max-age=1209600"" />
    <title>WebMail probably not configured</title>
    <link rel=""stylesheet"" href=""skins/AfterLogic/styles.css"" type=""text/css"" />
</head>
<body>
<div align=""center"" id=""content"" class=""wm_content"">
    <div class=""wm_logo"" id=""logo"" tabindex=""-1""></div>
    <div class=""wm_login_error"">WebMail could not find data folder. Check SettingsPath in Web.config</div>
</div>
    <div class=""wm_copyright"" id=""copyright"">
		Powered by <a href=""http://www.afterlogic.com/mailbee/webmail-pro.asp"" target=""_blank""> AfterLogic WebMail Pro</a><br>
Copyright &copy; 2002-2010 <a href=""http://www.afterlogic.com"" target=""_blank"">AfterLogic Corporation</a>
	</div>
</body>
</html>
");
                Response.End();
                return;
            }

            try
            {
                defaultTitle = Utils.EncodeJsSaveString(settings.SiteName);

                defaultSkin = settings.DefaultSkin;
                string[] supportedSkins = Utils.GetSupportedSkins((Page != null) ? Page.MapPath("skins") : string.Empty);
                if (Utils.GetCurrentSkinIndex(supportedSkins, defaultSkin) < 0)
                {
                    if (supportedSkins.Length > 0)
                    {
                        defaultSkin = supportedSkins[0];
                    }
                }
                defaultSkin = Utils.EncodeJsSaveString(defaultSkin);

                if (Request["lang"] != null && supportedLangs.ContainsKey(Request["lang"]))
                {
                    defaultLang = Request["lang"];
                    HttpCookie defLangCookie = new HttpCookie("awm_defLang");
                    defLangCookie.Value = defaultLang;
                    defLangCookie.Path  = HttpContext.Current.Request.ApplicationPath;
                    Response.AppendCookie(defLangCookie);
                }
                else if (Request.Cookies["awm_defLang"] != null && supportedLangs.ContainsKey(Request.Cookies["awm_defLang"].Value))
                {
                    defaultLang = Request.Cookies["awm_defLang"].Value;
                }
                if (string.IsNullOrEmpty(defaultLang))
                {
                    defaultLang = settings.DefaultLanguage;
                }
                defaultLangName = supportedLangs[defaultLang];
                _resMan         = (new WebmailResourceManagerCreator()).CreateResourceManager(defaultLang);

                if (defaultLang == "Hebrew" || defaultLang == "Arabic")
                {
                    _stylesRtl = true;
                    _rtl       = "true";
                }

                defaultIncServer = settings.IncomingMailServer;

                switch (settings.IncomingMailProtocol)
                {
                case IncomingMailProtocol.Pop3:
                {
                    defaultIncProtocol = POP3_PROTOCOL;
                    break;
                }

                case IncomingMailProtocol.Imap4:
                {
                    defaultIncProtocol = IMAP4_PROTOCOL;
                    break;
                }

                case IncomingMailProtocol.WMServer:
                {
                    defaultIncProtocol = WMSERVER_PROTOCOL;
                    break;
                }
                }

                defaultIncPort            = settings.IncomingMailPort;
                defaultOutServer          = settings.OutgoingMailServer;
                defaultOutPort            = settings.OutgoingMailPort;
                defaultUseSmtpAuth        = settings.ReqSmtpAuth;
                defaultSignMe             = false;
                defaultIsAjax             = settings.AllowAjax ? "true" : "false";
                defaultAllowAdvancedLogin = (settings.AllowAdvancedLogin) ? "true" : "false";
                defaultHideLoginMode      = (int)settings.HideLoginMode;
                defaultDomainOptional     = Utils.EncodeJsSaveString(settings.DefaultDomainOptional);

                pop3Selected     = (defaultIncProtocol == POP3_PROTOCOL) ? @" selected=""selected""" : "";
                imap4Selected    = (defaultIncProtocol == IMAP4_PROTOCOL) ? @" selected=""selected""" : "";
                wmserverSelected = (defaultIncProtocol == WMSERVER_PROTOCOL) ? @" selected=""selected""" : "";

                smtpAuthChecked = defaultUseSmtpAuth ? @" checked=""checked""" : "";

                signMeChecked = defaultSignMe ? @" checked=""checked""" : "";

                //for version without ajax
                errorClass = "wm_hide";                 //if there is no error
                errorDesc  = "";
                mode       = Request["mode"];           //mode = standard|advanced|submit
                switch (mode)
                {
                case "advanced":
                    DisplayAdvancedMode();
                    break;

                case "submit":
                    DisplayStandardMode();
                    globalEmail         = Request["email"];
                    globalLogin         = Request["login"];
                    globalPassword      = Request["password"];
                    globalSignMe        = Request["sign_me"];
                    globalAdvancedLogin = Request["advanced_login"];    //0|1
                    if (globalAdvancedLogin == "1" || (int)settings.HideLoginMode < 20)
                    {
                        if (!Validation.CheckIt(Validation.ValidationTask.Email, globalEmail))
                        {
                            errorDesc  = _resMan.GetString(Validation.ErrorMessage);
                            errorClass = "wm_login_error";
                            break;
                        }
                        globalEmail = Validation.Corrected;
                    }
                    if (globalAdvancedLogin == "1" || (int)settings.HideLoginMode != 10 && (int)settings.HideLoginMode != 11)
                    {
                        if (!Validation.CheckIt(Validation.ValidationTask.Login, globalLogin))
                        {
                            errorDesc  = _resMan.GetString(Validation.ErrorMessage);
                            errorClass = "wm_login_error";
                            break;
                        }
                        globalLogin = Validation.Corrected;
                    }
                    if (!Validation.CheckIt(Validation.ValidationTask.Password, globalPassword))
                    {
                        errorDesc  = _resMan.GetString(Validation.ErrorMessage);
                        errorClass = "wm_login_error";
                        break;
                    }

                    if (globalAdvancedLogin == "1")
                    {
                        globalIncServer   = Request["inc_server"];
                        globalIncProtocol = Request["inc_protocol"];
                        globalIncPort     = Request["inc_port"];
                        globalOutServer   = Request["out_server"];
                        globalOutPort     = Request["out_port"];
                        globalUseSmtpAuth = Request["smtp_auth"];
                        if (!Validation.CheckIt(Validation.ValidationTask.INServer, globalIncServer, globalAdvancedLogin))
                        {
                            errorDesc  = _resMan.GetString(Validation.ErrorMessage);
                            errorClass = "wm_login_error";
                            break;
                        }
                        globalIncServer = Validation.Corrected;
                        if (!Validation.CheckIt(Validation.ValidationTask.INPort, globalIncPort, globalAdvancedLogin))
                        {
                            errorDesc  = _resMan.GetString(Validation.ErrorMessage);
                            errorClass = "wm_login_error";
                            break;
                        }
                        globalIncPort = Validation.Corrected;
                        if (!Validation.CheckIt(Validation.ValidationTask.OUTServer, globalOutServer, globalAdvancedLogin))
                        {
                            errorDesc  = _resMan.GetString(Validation.ErrorMessage);
                            errorClass = "wm_login_error";
                            break;
                        }
                        globalOutServer = Validation.Corrected;
                        if (!Validation.CheckIt(Validation.ValidationTask.OUTPort, globalOutPort, globalAdvancedLogin))
                        {
                            errorDesc  = _resMan.GetString(Validation.ErrorMessage);
                            errorClass = "wm_login_error";
                            break;
                        }
                        globalOutPort = Validation.Corrected;
                    }
                    else
                    {
                        globalIncServer   = settings.IncomingMailServer;
                        globalIncProtocol = (settings.IncomingMailProtocol == IncomingMailProtocol.Imap4)
                                                                ? "1" : "0";
                        globalIncPort     = settings.IncomingMailPort.ToString();
                        globalOutServer   = settings.OutgoingMailServer;
                        globalOutPort     = settings.OutgoingMailPort.ToString();
                        globalUseSmtpAuth = settings.ReqSmtpAuth ? "1" : "0";
                    }


                    try
                    {
                        bool    advancedLogin = (string.Compare(globalAdvancedLogin, "1", true, CultureInfo.InvariantCulture) == 0) ? true : false;
                        bool    signAuto      = (string.Compare(globalSignMe, "1", true, CultureInfo.InvariantCulture) == 0) ? true : false;
                        bool    useSmtpAuth   = (string.Compare(globalUseSmtpAuth, "1", true, CultureInfo.InvariantCulture) == 0) ? true : false;
                        string  language      = Request["language"];
                        Account acct          = Account.LoginAccount(globalEmail, globalLogin, globalPassword,
                                                                     globalIncServer, (IncomingMailProtocol)Convert.ToInt32(globalIncProtocol),
                                                                     Convert.ToInt32(globalIncPort), globalOutServer, Convert.ToInt32(globalOutPort),
                                                                     useSmtpAuth, signAuto, advancedLogin, language);

                        if (acct != null)
                        {
                            if (globalSignMe == "1")
                            {
                                HttpCookie idAcctCookie = new HttpCookie("awm_autologin_id");
                                idAcctCookie.Value = acct.ID.ToString();
                                idAcctCookie.Path  = HttpContext.Current.Request.ApplicationPath;
                                Response.AppendCookie(idAcctCookie);

                                string     hash            = Utils.GetMD5DigestHexString(Utils.EncodePassword(acct.MailIncomingPassword));
                                HttpCookie autoLoginCookie = new HttpCookie("awm_autologin_data");
                                autoLoginCookie.Value = hash;
                                autoLoginCookie.Path  = HttpContext.Current.Request.ApplicationPath;
                                Response.AppendCookie(autoLoginCookie);
                            }

                            Session.Add(Constants.sessionAccount, acct);
                            if (acct.GetMailAtLogin)
                            {
                                Response.Redirect("basewebmail.aspx?check=1", false);
                            }
                            else
                            {
                                Response.Redirect("basewebmail.aspx", false);
                            }
                        }
                    }
                    catch (Exception message)
                    {
                        Log.WriteLine("Page_Load", "Login Account");
                        Log.WriteException(message);
                        errorDesc  = message.Message;
                        errorClass = "wm_login_error";                                 //if the error was occured
                    }
                    break;

                default:
                    DisplayStandardMode();
                    break;
                }
                //end for version without ajax

                string error = Request["error"] ?? string.Empty;
                if (error == "1")
                {
                    errorDesc  = "The previous session was terminated due to a timeout.";
                    errorClass = "wm_login_error";                     //if the error was occured
                }
                else
                {
                    HttpCookie idAcctCookie    = Request.Cookies["awm_autologin_id"];
                    HttpCookie autoLoginCookie = Request.Cookies["awm_autologin_data"];
                    if ((idAcctCookie != null) && (autoLoginCookie != null))
                    {
                        int id_acct = -1;
                        try
                        {
                            id_acct = int.Parse(idAcctCookie.Value);
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLine("Page_Load", "int.Parse");
                            Log.WriteException(ex);
                        }
                        Account acct = Account.LoadFromDb(id_acct, -1, false);

                        if (acct != null)
                        {
                            string encodePassword = Utils.GetMD5DigestHexString(Utils.EncodePassword(acct.MailIncomingPassword));
                            if (string.Compare(encodePassword, autoLoginCookie.Value, true, CultureInfo.InvariantCulture) == 0)
                            {
                                Session.Add(Constants.sessionAccount, acct);
                                idAcctCookie.Expires = DateTime.Now.AddDays(14);
                                if (settings.AllowAjax)
                                {
                                    Response.Redirect("webmail.aspx?check=1", false);
                                }
                                else
                                {
                                    Response.Redirect("basewebmail.aspx?check=1", false);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(ex);
            }
        }
Exemple #12
0
        public Account CreateAccount(bool def_acct, bool deleted, string email, IncomingMailProtocol mail_protocol,
                                     string mail_inc_host, string mail_inc_login, string mail_inc_pass, int mail_inc_port,
                                     string mail_out_host, string mail_out_login, string mail_out_pass, int mail_out_port,
                                     bool mail_out_auth, string friendly_nm, bool use_friendly_nm, DefaultOrder def_order,
                                     bool getmail_at_login, MailMode mail_mode, short mails_on_server_days, string signature,
                                     SignatureType signature_type, SignatureOptions signature_opt, string delimiter, long mailbox_size,
                                     FolderSyncType inboxSyncType, bool advanced_login, int id_domain, bool mailing_list, int imap_quota, string Namespace)
        {
            WebmailResourceManager resMan = (new WebmailResourceManagerCreator()).CreateResourceManager();

            //----- validate incoming data -----
            if ((email == null) || (email.Trim().Length == 0))
            {
                if (advanced_login)
                {
                    throw new WebMailException(resMan.GetString("WarningEmailFieldBlank"));
                }
            }
            Regex r = new Regex(@"[\w!#\$%\^\{}`~&'\+-=_\.]+@[\w-\.]+");
            Match m = r.Match(email);

            if (!m.Success)
            {
                throw new WebMailException("WarningCorrectEmail");
            }
            if ((mail_inc_login == null) || (mail_inc_login.Trim().Length == 0))
            {
                if (advanced_login)
                {
                    throw new WebMailException(resMan.GetString("WarningLoginFieldBlank"));
                }
            }
            if (mail_inc_login.IndexOfAny(new char[] { '"', '/', '\\', '*', '?', '<', '>', '|', ':' }) >= 0)
            {
                throw new WebMailException(resMan.GetString("WarningCorrectLogin"));
            }
            if (string.IsNullOrEmpty(mail_inc_pass))
            {
                throw new WebMailException(resMan.GetString("WarningPassBlank"));
            }
            if ((mail_inc_host == null) || (mail_inc_host.Trim().Length == 0))
            {
                throw new WebMailException(resMan.GetString("WarningIncServerBlank"));
            }
            r = new Regex(@"[^(\w-\.)]+");
            m = r.Match(mail_inc_host);
            if (m.Success)
            {
                if (advanced_login)
                {
                    throw new WebMailException(resMan.GetString("WarningCorrectIncServer"));
                }
            }
            if ((mail_inc_port < 0) || (mail_inc_port > 65535))
            {
                if (advanced_login)
                {
                    throw new WebMailException(resMan.GetString("WarningIncPortNumber"));
                }
            }
            if ((mail_out_host == null) || (mail_out_host.Trim().Length == 0))
            {
                if (advanced_login)
                {
                    throw new WebMailException(resMan.GetString("WarningOutServerBlank"));
                }
            }
            r = new Regex(@"[^(\w-\.)]+");
            m = r.Match(mail_out_host);
            if (m.Success)
            {
                if (advanced_login)
                {
                    throw new WebMailException(resMan.GetString("WarningCorrectOutServer"));
                }
            }
            if ((mail_out_port < 0) || (mail_out_port > 65535))
            {
                if (advanced_login)
                {
                    throw new WebMailException(resMan.GetString("WarningOutPortNumber"));
                }
            }
            //------ end validate incoming data --------


            WebmailSettings  settings   = (new WebMailSettingsCreator()).CreateWebMailSettings();
            Account          newAccount = null;
            DbManagerCreator creator    = new DbManagerCreator();
            DbManager        dbMan      = creator.CreateDbManager();

            try
            {
                dbMan.Connect();

                if (settings.EnableWmServer && mail_protocol == IncomingMailProtocol.WMServer)
                {
                    string          emailDomain  = EmailAddress.GetDomainFromEmail(email);
                    string          emailUser    = EmailAddress.GetAccountNameFromEmail(email);
                    WMServerStorage storage      = new WMServerStorage(null);
                    string[]        domains      = storage.GetDomainList();
                    bool            domainExists = false;

                    foreach (string domain in domains)
                    {
                        if (string.Compare(emailDomain, domain, true, CultureInfo.InvariantCulture) == 0)
                        {
                            Domain dom = Domain.GetDomain(emailDomain);
                            if (dom != null)
                            {
                                id_domain = dom.ID;
                            }

                            WMServerUser[] users             = storage.GetUserList(emailDomain);
                            bool           userExists        = false;
                            bool           mailingListExists = false;
                            foreach (WMServerUser user in users)
                            {
                                if (string.Compare(emailUser, user.Name, true, CultureInfo.InvariantCulture) == 0)
                                {
                                    if (string.Compare("U", user.Type, true, CultureInfo.InvariantCulture) == 0)
                                    {
                                        userExists = true;
                                    }
                                    else
                                    {
                                        mailingListExists = true;
                                    }
                                    break;
                                }
                            }
                            if (!userExists && !mailing_list || !mailingListExists && mailing_list)
                            {
                                if (!mailingListExists)
                                {
                                    storage.AddUser(emailDomain, emailUser, mail_inc_pass);
                                }
                                else
                                {
                                    throw new WebMailException(resMan.GetString("ErrorPOP3IMAP4Auth"));
                                }
                            }
                            domainExists = true;
                            break;
                        }
                    }

                    if (!domainExists)
                    {
                        throw new WebMailException(resMan.GetString("ErrorDomainExist"));
                    }
                }

                if (mail_protocol == IncomingMailProtocol.WMServer)
                {
                    delimiter = ".";
                }

                newAccount = dbMan.CreateAccount(_id, def_acct, deleted, email, mail_protocol, mail_inc_host,
                                                 mail_inc_login, mail_inc_pass, mail_inc_port, mail_out_host, mail_out_login, mail_out_pass,
                                                 mail_out_port, mail_out_auth, friendly_nm, use_friendly_nm, def_order, getmail_at_login,
                                                 mail_mode, mails_on_server_days, signature, signature_type, signature_opt, delimiter,
                                                 mailbox_size, id_domain, mailing_list, imap_quota, Namespace);
                newAccount.UserOfAccount = this;

                dbMan.DbAccount = newAccount;
                FileSystem fs = new FileSystem(email, newAccount.ID, true);
                if (mail_protocol != IncomingMailProtocol.WMServer)
                {
                    fs.CreateAccount();
                }

                if (mail_protocol == IncomingMailProtocol.Pop3)
                {
                    if (settings.AllowDirectMode && settings.DirectModeIsDefault)
                    {
                        inboxSyncType = FolderSyncType.DirectMode;
                    }

                    // -- this fix for gmail pop3 --
                    if (mail_inc_host == "pop.gmail.com")
                    {
                        inboxSyncType = FolderSyncType.AllEntireMessages;
                    }
                    // -----------------------------

                    if (!settings.StoreMailsInDb)
                    {
                        fs.CreateFolder(Constants.FolderNames.Inbox);
                    }
                    dbMan.CreateFolder(newAccount.ID, -1, FolderType.Inbox, Constants.FolderNames.Inbox, Constants.FolderNames.Inbox, inboxSyncType, false, 0);

                    if (!settings.StoreMailsInDb)
                    {
                        fs.CreateFolder(Constants.FolderNames.SentItems);
                    }
                    dbMan.CreateFolder(newAccount.ID, -1, FolderType.SentItems, Constants.FolderNames.SentItems, Constants.FolderNames.SentItems, FolderSyncType.DontSync, false, 1);

                    if (!settings.StoreMailsInDb)
                    {
                        fs.CreateFolder(Constants.FolderNames.Drafts);
                    }
                    dbMan.CreateFolder(newAccount.ID, -1, FolderType.Drafts, Constants.FolderNames.Drafts, Constants.FolderNames.Drafts, FolderSyncType.DontSync, false, 2);

                    if (!settings.StoreMailsInDb)
                    {
                        fs.CreateFolder(Constants.FolderNames.Spam);
                    }
                    dbMan.CreateFolder(newAccount.ID, -1, FolderType.Spam, Constants.FolderNames.Spam, Constants.FolderNames.Spam, FolderSyncType.DontSync, false, 3);

                    if (!settings.StoreMailsInDb)
                    {
                        fs.CreateFolder(Constants.FolderNames.Trash);
                    }
                    dbMan.CreateFolder(newAccount.ID, -1, FolderType.Trash, Constants.FolderNames.Trash, Constants.FolderNames.Trash, FolderSyncType.DontSync, false, 4);
                }
                else if (mail_protocol == IncomingMailProtocol.WMServer)
                {
                    MailServerStorage wmServerStorage = MailServerStorageCreator.CreateMailServerStorage(newAccount);
                    try
                    {
                        wmServerStorage.Connect();
                        FolderCollection fc = wmServerStorage.GetFolders();

                        Folder fld = fc[FolderType.SentItems];
                        if (fld == null)
                        {
                            string       fullPath = newAccount.Delimiter + Constants.FolderNames.SentItems;
                            const string name     = Constants.FolderNames.SentItems;
                            if (!settings.StoreMailsInDb)
                            {
                                fs.CreateFolder(Constants.FolderNames.SentItems);
                            }
                            fld = new Folder(newAccount.ID, -1, fullPath, name);
                            wmServerStorage.CreateFolder(fld);
                            dbMan.CreateFolder(newAccount.ID, -1, FolderType.SentItems, name, fullPath, FolderSyncType.AllHeadersOnly, false, 1);
                        }

                        fld = fc[FolderType.Drafts];
                        if (fld == null)
                        {
                            string       fullPath = newAccount.Delimiter + Constants.FolderNames.Drafts;
                            const string name     = Constants.FolderNames.Drafts;
                            if (!settings.StoreMailsInDb)
                            {
                                fs.CreateFolder(Constants.FolderNames.Drafts);
                            }
                            fld = new Folder(newAccount.ID, -1, fullPath, name);
                            wmServerStorage.CreateFolder(fld);
                            dbMan.CreateFolder(newAccount.ID, -1, FolderType.Drafts, name, fullPath, FolderSyncType.AllHeadersOnly, false, 2);
                        }

                        fld = fc[FolderType.Spam];
                        if (fld == null)
                        {
                            string       fullPath = newAccount.Delimiter + Constants.FolderNames.Spam;
                            const string name     = Constants.FolderNames.Spam;
                            if (!settings.StoreMailsInDb)
                            {
                                fs.CreateFolder(Constants.FolderNames.Spam);
                            }
                            fld = new Folder(newAccount.ID, -1, fullPath, name);
                            wmServerStorage.CreateFolder(fld);
                            dbMan.CreateFolder(newAccount.ID, -1, FolderType.Spam, name, fullPath, FolderSyncType.AllHeadersOnly, false, 3);
                        }

                        fld = fc[FolderType.Trash];
                        if (fld == null)
                        {
                            string       fullPath = newAccount.Delimiter + Constants.FolderNames.Trash;
                            const string name     = Constants.FolderNames.Trash;
                            if (!settings.StoreMailsInDb)
                            {
                                fs.CreateFolder(Constants.FolderNames.Trash);
                            }
                            fld = new Folder(newAccount.ID, -1, fullPath, name);
                            wmServerStorage.CreateFolder(fld);
                            dbMan.CreateFolder(newAccount.ID, -1, FolderType.Trash, name, fullPath, FolderSyncType.AllHeadersOnly, false, 4);
                        }

                        fld = fc[FolderType.Quarantine];
                        if (fld == null)
                        {
                            string       fullPath = newAccount.Delimiter + Constants.FolderNames.Quarantine;
                            const string name     = Constants.FolderNames.Quarantine;
                            if (!settings.StoreMailsInDb)
                            {
                                fs.CreateFolder(Constants.FolderNames.Quarantine);
                            }
                            fld = new Folder(newAccount.ID, -1, fullPath, name);
                            wmServerStorage.CreateFolder(fld);
                            dbMan.CreateFolder(newAccount.ID, -1, FolderType.Quarantine, name, fullPath, FolderSyncType.AllHeadersOnly, false, 5);
                        }

                        dbMan.CreateFoldersTree(fc);
                    }
                    catch (Exception ex)
                    {
                        Log.WriteException(ex);
                        throw new WebMailException(ex);
                    }
                }
                else if (mail_protocol == IncomingMailProtocol.Imap4)
                {
                    MailServerStorage imapStorage = MailServerStorageCreator.CreateMailServerStorage(newAccount);
                    try
                    {
                        imapStorage.Connect();
                        FolderCollection fc  = imapStorage.GetFolders();
                        Folder           fld = fc[FolderType.Inbox];
                        if (fld != null)
                        {
                            fld.SyncType = FolderSyncType.DirectMode;
                        }

//                        if (settings.AllowDirectMode && settings.DirectModeIsDefault)
//                        {
                        fc.ReSetSyncTypeToDirectMode();
//                        }

                        fld = fc[FolderType.Drafts];
                        if (fld == null)
                        {
                            if (!settings.StoreMailsInDb)
                            {
                                fs.CreateFolder(Constants.FolderNames.Drafts);
                            }
                            dbMan.CreateFolder(newAccount.ID, -1, FolderType.Drafts, Constants.FolderNames.Drafts, Constants.FolderNames.Drafts, FolderSyncType.DontSync, false, 2);
                        }

                        fld = fc[FolderType.SentItems];
                        if (fld == null)
                        {
                            if (!settings.StoreMailsInDb)
                            {
                                fs.CreateFolder(Constants.FolderNames.SentItems);
                            }
                            dbMan.CreateFolder(newAccount.ID, -1, FolderType.SentItems, Constants.FolderNames.SentItems, Constants.FolderNames.SentItems, FolderSyncType.DontSync, false, 1);
                        }

                        fld = fc[FolderType.Spam];
                        if (fld == null)
                        {
                            if (!settings.StoreMailsInDb)
                            {
                                fs.CreateFolder(Constants.FolderNames.Spam);
                            }
                            dbMan.CreateFolder(newAccount.ID, -1, FolderType.Spam, Constants.FolderNames.Spam, Constants.FolderNames.Spam, FolderSyncType.DontSync, false, 3);
                        }

                        fld = fc[FolderType.Trash];
                        if (fld == null && settings.Imap4DeleteLikePop3)
                        {
                            if (!settings.StoreMailsInDb)
                            {
                                fs.CreateFolder(Constants.FolderNames.Trash);
                            }
                            dbMan.CreateFolder(newAccount.ID, -1, FolderType.Trash, Constants.FolderNames.Trash, Constants.FolderNames.Trash, FolderSyncType.DontSync, false, 4);
                        }

                        newAccount.Delimiter = (fc.Count > 0) ? fc[0].ImapFolder.Delimiter : newAccount.Delimiter;

                        if (!settings.StoreMailsInDb)
                        {
                            fs.CreateFoldersTree(fc);
                        }
                        dbMan.CreateFoldersTree(fc);
                    }
                    catch (Exception ex)
                    {
                        Log.WriteException(ex);
                        throw new WebMailException(ex);
                    }
                    finally
                    {
                        imapStorage.Disconnect();
                    }
                }
            }
            catch (IOException ex)
            {
                Log.WriteException(ex);
                throw new WebMailException(ex);
            }
            catch (UnauthorizedAccessException ex)
            {
                Log.WriteException(ex);
                throw new WebMailException(ex);
            }
            catch (WebMailException ex)
            {
                Log.WriteException(ex);
                if (newAccount != null)
                {
                    if (dbMan.IsConnected)
                    {
                        dbMan.DeleteAccount(newAccount.ID);
                    }
                    else
                    {
                        dbMan.Connect();
                        dbMan.DeleteAccount(newAccount.ID);
                    }
                }
                throw;
            }
            finally
            {
                dbMan.Disconnect();
            }
            return(newAccount);
        }