Esempio n. 1
0
        /// <summary>
        /// Gets the imap client.
        /// </summary>
        /// <returns>Imap 4 client.</returns>
        public Imap4Client GetImapClient()
        {
            string imapServer = _configurationPropertiesProvider.GetProperty(SettingKeyNames.ImapServer);
            int imapPort = _configurationPropertiesProvider.GetPropertyInt(SettingKeyNames.ImapPort);

            // Retrieves the Current User Context
            UserInformationDto info = _userInformationDtoFactory.CreateUserInformationDto();

            // Retrieves the corresponding Staff record for the current user
            Staff staff = _sessionProvider.GetSession().QueryOver<Staff>().Where(s => s.Key == info.StaffKey).SingleOrDefault();

            //string username = "******";
            //string password = "******";

            string username = null;
            string password = null;

            if (staff.DirectAddressCredential.DirectAddress != null)
            {
                username = staff.DirectAddressCredential.DirectAddress.Address;
                password = staff.DirectAddressCredential.DirectAddressPassword;
            }

            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                throw new ApplicationException("Username/password are not provided to access IMAP mail server.");
            }

            var imap4Client = new Imap4Client();
            imap4Client.Connect(imapServer, imapPort, username, password);

            return imap4Client;
        }
        private void AuthenticateImapPlain(Imap4Client imap)
        {
            switch (Account.IncomingEncryptionType)
            {
                case EncryptionType.StartTLS:
                    _log.Info("IMAP StartTLS connecting to {0}", Account.EMail);
                    imap.ConnectTLS(Account.Server, Account.Port);
                    break;
                case EncryptionType.SSL:
                    _log.Info("IMAP SSL connecting to {0}", Account.EMail);
                    imap.ConnectSsl(Account.Server, Account.Port);
                    break;
                case EncryptionType.None:
                    _log.Info("IMAP connecting to {0}", Account.EMail);
                    imap.Connect(Account.Server, Account.Port);
                    break;
            }

            _log.Info("IMAP connecting OK {0}", Account.EMail);

            _log.Info("IMAP logging in to {0}", Account.EMail);

            if (Account.AuthenticationTypeIn == SaslMechanism.Login)
            {
                imap.Login(Account.Account, Account.Password, "");
            }
            else
            {
                imap.Authenticate(Account.Account, Account.Password, Account.AuthenticationTypeIn);
            }

            _log.Info("IMAP logged in to {0}", Account.EMail);
        }
Esempio n. 3
0
 public void Login(object sender, System.EventArgs e)
 {
     try
     {
         ActiveUp.Net.Mail.Imap4Client imap4Client = new ActiveUp.Net.Mail.Imap4Client();
         imap4Client.Connect((string)Application["server\uFFFD"], System.Convert.ToInt32(Application["port\uFFFD"]));
         System.Web.Security.FormsAuthentication.SetAuthCookie(iLogin.Text + "|\uFFFD" + iPassword.Text, false);
         imap4Client.Login(iLogin.Text, iPassword.Text);
         Session.Add("login\uFFFD", iLogin.Text);
         Session.Add("imapobject\uFFFD", imap4Client);
         System.Web.HttpCookie httpCookie = new System.Web.HttpCookie("login\uFFFD", iLogin.Text);
         System.DateTime dateTime = System.DateTime.Now;
         httpCookie.Expires = dateTime.AddMonths(2);
         Response.Cookies.Add(httpCookie);
         Visible = false;
         EnableViewState = false;
      //   ((_Default)Page).SetWebmailLanguage(null, null);
         //BoundMailboxContent.BoundTopNavigation.Enable();
         //BoundMailboxContent.BoundTree.LoadTrees();
         //BoundMailboxContent.BoundTopNavigation.LoadList();
         //BoundMailboxContent.LoadMailbox(Application["startfolder\uFFFD"].ToString(), true);
     }
     catch (System.Exception e1)
     {
         Visible = true;
         EnableViewState = true;
         iLogin.Text = System.String.Empty;
         //    Page.RegisterStartupScript("ShowError\uFFFD", "<script>ShowErrorDialog('\uFFFD" + Language.Get(Server.MapPath("languages/\uFFFD"), Application["defaultlanguage\uFFFD"].ToString()).Words[96].ToString() + "','\uFFFD" + System.Text.RegularExpressions.Regex.Escape(e1.Message + e1.StackTrace).Replace("'\uFFFD", "\\'\uFFFD") + "');</script>\uFFFD");
         Page.RegisterStartupScript("ShowError\uFFFD", "<script>ShowErrorDialog('\uFFFD" + Language.Get(Server.MapPath("languages/"), Application["defaultlanguage\uFFFD"].ToString()).Words[96].ToString() + "','\uFFFD" + System.Text.RegularExpressions.Regex.Escape(e1.Message + e1.StackTrace).Replace("'\uFFFD", "\\'\uFFFD") + "');</script>\uFFFD");
     }
 }
Esempio n. 4
0
        public void Mail_holen(Action<Mail> continueWith) {
            using (var imap = new Imap4Client()) {
                imap.Connect(mailAccess.Server);
                imap.Login(mailAccess.Username, mailAccess.Password);

                var box = imap.SelectMailbox("inbox");
                var ids = box.Search("OR (CC @cc.lieser-online.de) (HEADER Envelope-To @cc.lieser-online.de)");
                var fetch = box.Fetch;
                foreach (var id in ids) {
                    var message = fetch.MessageObject(id);

                    var mail = new Mail {
                        Id = id.ToString(), 
                        From = message.From.Email, 
                        To = message.To.Select(x => x.Email).ToArray(), 
                        Cc = message.Cc.Select(x => x.Email).ToArray(),
                        Bcc = message.HeaderFields["Envelope-To"], 
                        Subject = message.Subject, 
                        Text = message.BodyText.Text
                    };
                    continueWith(mail);
                }
            }
            continueWith(null); // End-of-Stream signalisieren!!
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("Start work");

            string sHostPop = "pop.googlemail.com";
            string sHostImap = "imap.googlemail.com";
            int nPort = 995;
            string sUserName = "******";
            string sPasword = "theSimpsons";

            try
            {
                string sEml = @"E:\ut8_encripted_teamlab.eml";
                
                ActiveUp.Net.Mail.Message m = 
                ActiveUp.Net.Mail.Parser.ParseMessageFromFile(sEml);
                var header = ActiveUp.Net.Mail.Parser.ParseHeader(sEml);
                
                Pop3Client pop = new Pop3Client();

                // Connect to the pop3 client
                pop.ConnectSsl(sHostPop, nPort, "recent:" + sUserName, sPasword);

                if (pop.MessageCount > 0)
                {
                    ActiveUp.Net.Mail.Message message = pop.RetrieveMessageObject(4);
                    string sHtml = message.BodyHtml.Text;
                }
                else
                    System.Console.WriteLine("No letters!");

                pop.Disconnect();

                Imap4Client imap = new Imap4Client();

                imap.ConnectSsl(sHostImap, 993);

                imap.Login(sUserName, sPasword);

                Mailbox inbox = imap.SelectMailbox("inbox");
                
                if (inbox.MessageCount > 0)
                {
                    ActiveUp.Net.Mail.Message message = inbox.Fetch.MessageObject(6);
                    string sHtml = message.BodyHtml.Text;
                }

                imap.Disconnect();

            }
            catch (Exception ex)
            {
                System.Console.Write("\r\n" + ex);
            }

            System.Console.WriteLine("Stop work");

            System.Console.ReadKey();
        }
Esempio n. 6
0
        private static Mailbox Connect(Imap4Client server, string host, int port, string username, string password, string folder, bool useSsl)
        {
            if (useSsl)
                server.ConnectSsl(host, port);
            else
                server.Connect(host, port);
            server.Login(username, password);

            return server.AllMailboxes.Cast<Mailbox>().First(x => x.Name == folder);
        }
Esempio n. 7
0
 private void btnClick_Click(object sender, EventArgs e)
 {
     Imap4Client client = new Imap4Client();
     client.Connect(txtHost.Text, int.Parse(txtPort.Text), txtUser.Text, txtPassword.Text);
     Imap4Result result = new Imap4Result();
     result.Imap = client;
     result.ShowDialog();
     client.Disconnect();
     System.Threading.Thread.Sleep(0);
 }
Esempio n. 8
0
        private void _bSearch_Click(object sender, EventArgs e)
        {
            // We create Imap client
            Imap4Client imap = new Imap4Client();

            try
            {
                // We connect to the imap4 server
                imap.Connect(_tbImap4Server.Text);

                this.AddLogEntry(string.Format("Connection to {0} successfully", _tbImap4Server.Text));

                // Login to mail box
                imap.Login(_tbUserName.Text, _tbPassword.Text);

                this.AddLogEntry(string.Format("Login to {0} successfully", _tbImap4Server.Text));

                Mailbox inbox = imap.SelectMailbox("inbox");

                // We gets the message matching the search criteria.
                MessageCollection messages = inbox.SearchParse("searchcritiria");
                
                if (messages.Count > 0)
                {
                    for (int n = 0; n < messages.Count; n++)
                    {
                        this.AddLogEntry(string.Format("Message ({0}) : {1}", n.ToString(), messages[n].Subject));
                    }
                }

                else
                {
                    this.AddLogEntry("There is no message using this search pattern");
                }

            }

            catch (Imap4Exception iex)
            {
                this.AddLogEntry(string.Format("Imap4 Error: {0}", iex.Message));
            }

            catch (Exception ex)
            {
                this.AddLogEntry(string.Format("Failed: {0}", ex.Message));
            }

            finally
            {
                if (imap.IsConnected)
                {
                    imap.Disconnect();
                }
            }
        }
Esempio n. 9
0
        private void _bRetrieveMessages_Click(object sender, EventArgs e)
        {
            // We create Imap client
            imap = new Imap4Client();

            try
            {
                // We connect to the imap4 server
                imap.Connect(_tbImap4Server.Text);

                this.AddLogEntry(string.Format("Connection to {0} successfully", _tbImap4Server.Text));

                // Login to mail box
                imap.Login(_tbUserName.Text, _tbPassword.Text);

                this.AddLogEntry(string.Format("Login to {0} successfully", _tbImap4Server.Text));

                inbox = imap.SelectMailbox("inbox");
                if (inbox.MessageCount > 0)
                {
                    for (int i = 1; i < inbox.MessageCount + 1; i++)
                    {
                        ActiveUp.Net.Mail.Message message = inbox.Fetch.MessageObject(i);
                        ListViewItem lvi = new ListViewItem();
                        lvi.Text = i.ToString("0000");
                        lvi.SubItems.AddRange(new string[] { message.Subject});
                        lvi.Tag = message;

                        _lvMessages.Items.Add(lvi);

                        this.AddLogEntry(string.Format("{3} Subject: {0} From :{1} Message Body {2}"
                                        , message.Subject, message.From.Email, message.BodyText, i.ToString("0000")));
                    }
                }

                else
                {
                    this.AddLogEntry("There is no unanswered messages in the imap4 account");
                }

            }

            catch (Imap4Exception iex)
            {
                this.AddLogEntry(string.Format("Imap4 Error: {0}", iex.Message));
            }

            catch (Exception ex)
            {
                this.AddLogEntry(string.Format("Failed: {0}", ex.Message));
            }
   
        }
        private void _bRetrieveMessage_Click(object sender, EventArgs e)
        {
            // We create Imap client
            Imap4Client imap = new Imap4Client();

            try
            {
                // We connect to the imap4 server
                imap.ConnectSsl(_tbImap4Server.Text);

                this.AddLogEntry(string.Format("Connection to {0} successfully", _tbImap4Server.Text));

                // Login to mail box
                imap.Login(_tbUserName.Text, _tbPassword.Text);

                this.AddLogEntry(string.Format("Login to {0} successfully", _tbImap4Server.Text));

                Mailbox inbox = imap.SelectMailbox("inbox");
                if (inbox.MessageCount > 0)
                {
                    Header header = inbox.Fetch.HeaderObject(1);

                    this.AddLogEntry(string.Format("Subject: {0} From :{1} ", header.Subject, header.From.Email));
                }

                else
                {
                    this.AddLogEntry("There is no message in the imap4 account");
                }

            }

            catch (Imap4Exception iex)
            {
                this.AddLogEntry(string.Format("Imap4 Error: {0}", iex.Message));
            }

            catch (Exception ex)
            {
                this.AddLogEntry(string.Format("Failed: {0}", ex.Message));
            }

            finally
            {
                if (imap.IsConnected)
                {
                    imap.Disconnect();
                }
            }
        }
Esempio n. 11
0
        public void Mail_verschieben(string id, Action onEndOfStream) {
            if (id == null) {
                onEndOfStream();
                return;
            }

            using (var imap = new Imap4Client()) {
                imap.Connect(mailAccess.Server);
                imap.Login(mailAccess.Username, mailAccess.Password);

                var box = imap.SelectMailbox("inbox");
                box.MoveMessage(int.Parse(id), "Archiv");
            }
        }
        private void AuthenticateImapGoogleOAuth2(Imap4Client imap)
        {
            var auth = new GoogleOAuth2Authorization();
            var granted_access = auth.RequestAccessToken(Account.RefreshToken);
            if (granted_access == null) return;
            _log.Info("IMAP SSL connecting to {0}", Account.EMail);
            imap.ConnectSsl(Account.Server, Account.Port);

            _log.Info("IMAP connecting OK {0}", Account.EMail);

            _log.Info("IMAP logging to {0} via OAuth 2.0", Account.EMail);
            imap.LoginOAuth2(Account.Account, granted_access.AccessToken);
            _log.Info("IMAP logged to {0} via OAuth 2.0", Account.EMail);
        }
Esempio n. 13
0
        private void _bEmptyMailbox_Click(object sender, EventArgs e)
        {
            // We create Imap client
            Imap4Client imap = new Imap4Client();

            try
            {
                // We connect to the imap4 server
                imap.Connect(_tbImap4Server.Text);

                this.AddLogEntry(string.Format("Connection to {0} successfully", _tbImap4Server.Text));

                // Login to mail box
                imap.Login(_tbUserName.Text, _tbPassword.Text);

                this.AddLogEntry(string.Format("Login to {0} successfully", _tbImap4Server.Text));

                if (_tbMailboxToEmpty.Text.Length > 0)
                {
                    Mailbox mailbox = imap.SelectMailbox(_tbMailboxToEmpty.Text);
                    mailbox.Empty(false);
                    this.AddLogEntry(string.Format("Mailbox {0} successfully empty",_tbMailboxToEmpty.Text));
                }

                else
                {
                    this.AddLogEntry("You have to set a mailbox name to empty");
                }

            }

            catch (Imap4Exception iex)
            {
                this.AddLogEntry(string.Format("Imap4 Error: {0}", iex.Message));
            }

            catch (Exception ex)
            {
                this.AddLogEntry(string.Format("Failed: {0}", ex.Message));
            }

            finally
            {
                if (imap.IsConnected)
                {
                    imap.Disconnect();
                }
            }
        }
        private void AuthenticateImapGoogleOAuth2(Imap4Client imap)
        {
            var auth = new GoogleOAuth2Authorization(_log);
            var granted_access = auth.RequestAccessToken(Account.RefreshToken);
            if (granted_access == null) 
                throw new DotNetOpenAuth.Messaging.ProtocolException("Access denied");
            _log.Info("IMAP SSL connecting to {0}", Account.EMail);
            imap.ConnectSsl(Account.Server, Account.Port);

            _log.Info("IMAP connecting OK {0}", Account.EMail);

            _log.Info("IMAP logging to {0} via OAuth 2.0", Account.EMail);
            imap.LoginOAuth2(Account.Account, granted_access.AccessToken);
            _log.Info("IMAP logged to {0} via OAuth 2.0", Account.EMail);
        }
        private void _bRetrieveMessageList_Click(object sender, EventArgs e)
        {
            // We create Imap client
            Imap4Client imap = new Imap4Client();

            try
            {
                // We connect to the imap4 server
                imap.Connect(_tbImap4Server.Text);

                this.AddLogEntry(string.Format("Connection to {0} successfully", _tbImap4Server.Text));

                // Login to mail box
                imap.Login(_tbUserName.Text, _tbPassword.Text);

                this.AddLogEntry(string.Format("Login to {0} successfully", _tbImap4Server.Text));

                Mailbox inbox = imap.SelectMailbox("inbox");

                MessageCollection mc = new MessageCollection();

                for (int n = 1; n < inbox.MessageCount + 1; n++)
                {
                    ActiveUp.Net.Mail.Message newMessage = inbox.Fetch.MessageObject(n);
                    mc.Add(newMessage);
                    this.AddLogEntry(string.Format("Message ({0}) : {1}", n.ToString(), newMessage.Subject));
                }
                
            }

            catch (Imap4Exception iex)
            {
                this.AddLogEntry(string.Format("Imap4 Error: {0}", iex.Message));
            }

            catch (Exception ex)
            {
                this.AddLogEntry(string.Format("Failed: {0}", ex.Message));
            }

            finally
            {
                if (imap.IsConnected)
                {
                    imap.Disconnect();
                }
            }
        }
Esempio n. 16
0
        public void Spike() {
            var mailAccess = MailAccessRepository.LoadFrom("mailfollowup.spikes.mail.access.txt", Assembly.GetExecutingAssembly());

            using (var imap = new Imap4Client()) {
                imap.Connect(mailAccess.Server);
                imap.Login(mailAccess.Username, mailAccess.Password);

                var box = imap.SelectMailbox("Archiv");
                var ids = box.Search("OR OR (TO @cc.lieser-online.de) (CC @cc.lieser-online.de) (HEADER Envelope-To @cc.lieser-online.de)");
                var fetch = box.Fetch;
                foreach (var id in ids) {
                    var message = fetch.MessageObject(id);
                    Console.WriteLine("{0}: {1}", message.From.Email, message.Subject);
                    //box.MoveMessage(id, "followup");
                }
            }
        }
Esempio n. 17
0
        private static void Connect(string host, int port, string username, string password, string folder, bool useSsl, Action<Imap4Client, Mailbox> whatToDo)
        {
            using (var server = new Imap4Client())
            {
                var mailbox = Connect(server, host, port, username, password, folder, useSsl);

                try
                {
                    whatToDo.Invoke(server, mailbox);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }

                server.Close();
            }
        }
        public void Connect()
        {
            Imap4Client client;
            //Create a new ImapClient and connect with the server and login with the correct username and password
            client = new Imap4Client();
            client.ConnectSsl(server, port);
            client.Login(username, password);

            //If the client is connected the test passes or else it will fail
            if (client.IsConnected)
            {
                Assert.IsTrue(true);
            }
            else
            {
                Assert.IsTrue(false);
            }
        }
        private void _bRetrieveAll_Click(object sender, EventArgs e)
        {
            // We create Imap client
            Imap4Client imap = new Imap4Client();

            try
            {
                // We connect to the imap4 server
                imap.Connect(_tbImap4Server.Text);

                this.AddLogEntry(string.Format("Connection to {0} successfully",_tbImap4Server.Text));

                // Login to mail box
                imap.Login(_tbUserName.Text, _tbPassword.Text);

                this.AddLogEntry(string.Format("Login to {0} successfully",_tbImap4Server.Text));

                //Display all mailbox names on the account.
                foreach (Mailbox mailbox in imap.Mailboxes)
                {
                    this.AddLogEntry(string.Format("Mailbox : {0}",mailbox.Name));
                }
            }

            catch (Imap4Exception iex)
            {
                this.AddLogEntry(string.Format("Imap4 Error: {0}", iex.Message));
            }

            catch (Exception ex)
            {
                this.AddLogEntry(string.Format("Failed: {0}", ex.Message));
            }

            finally
            {
                if (imap.IsConnected)
                {
                    imap.Disconnect();
                }
            }
        }
        private void AuthenticateImap(Imap4Client imap)
        {
            if (Account.RefreshToken != null)
            {
                var service_type = (AuthorizationServiceType)Account.ServiceType;

                switch (service_type)
                {
                    case AuthorizationServiceType.Google:
                        AuthenticateImapGoogleOAuth2(imap);
                        break;
                    default:
                        AuthenticateImapPlain(imap);
                        break;
                }
            }
            else
            {
                AuthenticateImapPlain(imap);
            }
        }
Esempio n. 21
0
        private static BaseProtocolClient BuildMailClient(MailClientType type)
        {
            BaseProtocolClient client;
            switch (type)
            {
                case MailClientType.Imap: 
                    client = new Imap4Client();
                    break;
                case MailClientType.Pop3: 
                    client = new Pop3Client();
                    break;
                case MailClientType.Smtp: 
                    client = new SmtpClient();
                    break;
                default:
                    throw new ArgumentException(String.Format("Unknown client type: {0}", type));
            }

            try
            {
                client.SendTimeout = Convert.ToInt32(WebConfigurationManager.AppSettings["mail.send-tcp-timeout"] ?? "30000");
                client.ReceiveTimeout = Convert.ToInt32(WebConfigurationManager.AppSettings["mail.recieve-tcp-timeout"] ?? "30000");
                client.CertificatePermit = Convert.ToBoolean(WebConfigurationManager.AppSettings["mail.certificate-permit"] ?? "false");
            }
            catch (Exception e)
            {
                client.ReceiveTimeout = 30000;
                client.SendTimeout = 30000;
                client.CertificatePermit = false;

                var logger = LogManager.GetLogger("MailBoxManager");
                var message = String.Format("Problems with config parsing for SendTimeout: {0} or RecieveTimeout: {1}. Values was reseted to default - 30000.\n",
                        WebConfigurationManager.AppSettings["mail.send-tcp-timeout"],
                        WebConfigurationManager.AppSettings["mail.recieve-tcp-timeout"]);
                logger.DebugException(message, e);
            }

            return client;
        }
Esempio n. 22
0
        /// <summary>
        /// Connect the imap4 client.
        /// </summary>
        /// <param name="accountInfo">The account information.</param>
        public void Connect(AccountSettings.AccountInfo accountInfo)
        {
            if (accountInfo != null && accountInfo.MailAccountType == AccountType.IMAP)
            {
                this.Imap4Client = new Imap4Client();

                int port = accountInfo.InPort;
                bool ssl = accountInfo.IncomingIsSSL;
                string serverName = accountInfo.IncomingServerName;
                string user = accountInfo.EmailAddress;
                string password = accountInfo.Password;
                bool useInPort = accountInfo.InPortEnabled;

                if (ssl)
                {
                    if (useInPort)
                    {
                        this.Imap4Client.ConnectSsl(serverName, port);
                    }
                    else
                    {
                        this.Imap4Client.ConnectSsl(serverName);
                    }
                }
                else
                {
                    if (useInPort)
                    {
                        this.Imap4Client.Connect(serverName, port);
                    }
                    else
                    {
                        this.Imap4Client.Connect(serverName);
                    }
                }

                this.Imap4Client.Login(user, password);
            }
        }
        private void StartIdleProcess(object sender, DoWorkEventArgs e)
        {
            // Get the BackgroundWorker that raised this event.
            //BackgroundWorker worker = sender as BackgroundWorker;

            if (imap != null && imap.IsConnected)
            {
                imap.StopIdle();
                imap.Disconnect();
            }

            imap = new Imap4Client();
            imap.NewMessageReceived += new NewMessageReceivedEventHandler(NewMessageReceived);
            //worker.ReportProgress(1, "Connection...");
            imap.Connect(thisForm.imap4ServerTextbox.Text);
            //worker.ReportProgress(0, "Login...");
            imap.Login(thisForm.usernameTextbox.Text, thisForm.passwordTextbox.Text);
            //worker.ReportProgress(0, "Select 'inbox'...");
            imap.SelectMailbox("inbox");
            //worker.ReportProgress(0, "Start idle...");
            imap.StartIdle();
        }
Esempio n. 24
0
 public void CONNECT_IMAP()
 {
     try
     {
         GMAIL_IMAP = new Imap4Client();
         GMAIL_IMAP.ConnectSsl(SERVER, PORTA);
         GMAIL_IMAP.Login(USER, PWD);
         bIMAP_ERROR = false;
         btnRECONNECT.Visible = false;
     }
     catch (Exception errCONN)
     {
         nIcon.Icon = MyGNotifier.Properties.Resources.MyGNotify_Empty_Error;
         btnRECONNECT.Visible = true;
         TimerGNotifier.Enabled = false;
         bIMAP_ERROR = true;
         rtError.Text += DateTime.Now.ToString() + "-> ERRORE CONNESSIONE IMAP:\n" + errCONN.Message + "\n------------------\n";
         MGN_ERROR = DateTime.Now.ToString() + "-> ERRORE CONNESSIONE IMAP: " + errCONN.Message;
         if (MyGNotifier.Properties.Settings.Default.MAIN_AUTO_NOTIFY_ERROR)
         {
             NOTIFY_ERROR(MGN_ERROR);
         }
     }
 }
Esempio n. 25
0
        private void btnConnectionTest_Click(object sender, EventArgs e)
        {
            if (TimerGNotifier.Enabled)
            {
                TimerGNotifier.Enabled = false;
                StartStopTimer();
            }

            bool bOK = true;
            string RESULT = "";

            # region CONNECTION ATTEMPT
            Imap4Client imap = new Imap4Client();
            try
            {
                imap.ConnectSsl(txtIMAP_SERVER.Text, Convert.ToInt16(txtPORTA_IMAP.Text));
            }
            catch
            {
                bOK = false;
                RESULT += "IMPOSSIBILE STABILIRE CONNESSINE SSL!\nVERIFICARE SERVER e PORTA!\n";
            }
            try
            {
                imap.Login(txtUSERNAME.Text, txtPASSWORD.Text);
            }
            catch
            {
                bOK = false;
                RESULT += "NOME UTENTE O PASSWORD NON CORRETTI!\n";
            }
            try
            {
                imap.Disconnect();
            } catch { }

            # endregion

            if (bOK)
            {
                MessageBox.Show("LE IMPOSTAZIONI DI CONNESSIONE SONO CORRETTE!", "CONNESSIONE OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("LE IMPOSTAZIONI DI CONNESSIONE NON SONO CORRETTE!\nPREGO VERIFICARE QUANTO SEGUE:\n" + RESULT, "ATTENZIONE", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            if (bOK)
            {
                if (!TimerGNotifier.Enabled)
                {
                    TimerGNotifier.Enabled = true;
                    StartStopTimer();
                }
            }
        }
Esempio n. 26
0
        public void MYG_IMAP_READ_AND_MARK_ALWAYS_CONNECT()
        {
            int iCountNew = 0;
            string sNewMsgs = "";
            DateTime dtInizio = DateTime.Now;
            nIcon.Icon = MyGNotifier.Properties.Resources.MyGNotify_Checking;
            nIcon.Text = "STO CONTROLLANDO LA CASELLA DI POSTA...";

            Imap4Client imap = new Imap4Client();
            btnRECONNECT.Visible = false;

            # region CONNECT
            try
            {
                imap = new Imap4Client();
                imap.ConnectSsl(SERVER, PORTA);
                imap.Login(USER, PWD);
                bIMAP_ERROR = false;
            }
            catch (Exception errCONN)
            {
                nIcon.Icon = MyGNotifier.Properties.Resources.MyGNotify_Empty_Error;
                nIcon.Text = "ERRORE CONNESSIONE IMAP:\n" + errCONN.Message;

                bIMAP_ERROR = true;
                rtError.Text += DateTime.Now.ToString() + "-> ERRORE CONNESSIONE IMAP:\n" + errCONN.Message + "\n------------------\n";
                MGN_ERROR = DateTime.Now.ToString() + "-> ERRORE CONNESSIONE IMAP: " + errCONN.Message;
                if (MyGNotifier.Properties.Settings.Default.MAIN_AUTO_NOTIFY_ERROR)
                {
                    if (MyGNotifier.Properties.Settings.Default.MAIN_RAD_NOTIFIER)
                    {
                        RAD_NOTIFY_ERROR(MGN_ERROR);
                    }
                    else
                    {
                        NOTIFY_ERROR(MGN_ERROR);
                    }
                }
            }
            # endregion

            # region ELABORA MESSAGGI
            if (!bIMAP_ERROR)
            {
                try
                {
                    imap.Command("capability");
                    Mailbox inbox = imap.SelectMailbox("inbox");
                    int[] ids = inbox.Search("UNSEEN");
                    if (ids.Length > 0)
                    {
                        ActiveUp.Net.Mail.Message msg = null;

                        for (var i = 0; i < ids.Length; i++)
                        {
                            msg = inbox.Fetch.MessageObject(ids[i]);

                            string UNIQUE_ID = msg.Date.ToString() + msg.From.ToString();
                            if (!MSGS_ID.Contains(UNIQUE_ID))
                            {
                                iCountNew++;
                                MSGS_ID.Add(UNIQUE_ID);

                                rtLog.Text += DateTime.Now.ToString() + "\n";
                                rtLog.Text += "DATA: " + msg.Date + "\n";
                                rtLog.Text += "MITTENTE: " + msg.From + "\n";
                                rtLog.Text += "OGGETTO: " + msg.Subject + "\n";
                                rtLog.Text += "----------------------------\n";

                                sNewMsgs += "DATA: " + msg.Date + "\n";
                                sNewMsgs += "MITTENTE: " + msg.From + "\n";
                                sNewMsgs += "OGGETTO: " + msg.Subject + "\n";
                                sNewMsgs += "---------------------------\n";
                            }
                            //mark as unread
                            var flags = new FlagCollection();
                            flags.Add("Seen");
                            inbox.RemoveFlags(ids[i], flags);
                        }
                        if (iCountNew > 0)
                        {
                            iLastCOUNT = iCountNew;
                            MSGS_DETAILS = sNewMsgs;
                            nIcon.Icon = MyGNotifier.Properties.Resources.MyGNotify_Check;
                            nIcon.Text = iCountNew > 1 ? "SONO PRESENTI " + iCountNew + " NUOVI MESSAGGI" : "E' PRESENTE 1 NUOVO MESSAGGIO!";

                            bNewMsgICON = true;
                            NEW_MSGS = true;
                        }
                        else
                        {
                            nIcon.Icon = MyGNotifier.Properties.Resources.MyGNotify_Empty_Gray;
                            NEW_MSGS = false;
                        }
                    }
                    else
                    {
                        nIcon.Icon = MyGNotifier.Properties.Resources.MyGNotify_Empty_Gray;
                        NEW_MSGS = false;
                    }

                }
                catch (Exception err)
                {
                    nIcon.Icon = MyGNotifier.Properties.Resources.MyGNotify_Empty_Error;
                    rtError.Text += DateTime.Now.ToString() + "-> ERRORE CONNESSIONE IMAP:\n" + err.Message + "\n------------------\n"; ;
                    MGN_ERROR = DateTime.Now.ToString() + "-> ERRORE ELABORAZIONE IMAP: " + err.Message;
                    if (MyGNotifier.Properties.Settings.Default.MAIN_AUTO_NOTIFY_ERROR)
                    {
                        if (MyGNotifier.Properties.Settings.Default.MAIN_RAD_NOTIFIER)
                        {
                            RAD_NOTIFY_ERROR(MGN_ERROR);
                        }
                        else
                        {
                            NOTIFY_ERROR(MGN_ERROR);
                        }
                    }
                }
            }
            else
            {
                rtLog.Text += "\n---------------\n" + DateTime.Now.ToString() + "-> ERRORE CONNESSIONE IMAP!\n---------------\n";
            }
            # endregion

            # region DISCONNECT
            try
            {
                imap.Disconnect();
            }
            catch (Exception err)
            {
                nIcon.Icon = MyGNotifier.Properties.Resources.MyGNotify_Empty_Error;
                nIcon.Text = "ERRORE DISCONNESSIONE IMAP:\n" + err.Message;

                rtError.Text += DateTime.Now.ToString() + "-> ERRORE DISCONNESSIONE IMAP:\n" + err.Message + "\n------------------\n"; ;
                MGN_ERROR = DateTime.Now.ToString() + "-> ERRORE DISCONNESSIONE IMAP: " + err.Message;
                if (MyGNotifier.Properties.Settings.Default.MAIN_AUTO_NOTIFY_ERROR)
                {
                    if (MyGNotifier.Properties.Settings.Default.MAIN_RAD_NOTIFIER)
                    {
                        RAD_NOTIFY_ERROR(MGN_ERROR);
                    }
                    else
                    {
                        NOTIFY_ERROR(MGN_ERROR);
                    }
                }
            }
            # endregion

            if (bNewMsgICON) { nIcon.Icon = MyGNotifier.Properties.Resources.MyGNotify_Check; }
            else
            {
                if (!NEW_MSGS)
                {
                    nIcon.Text = "NESSUN NUOVO MESSAGGIO!";
                }
            }

            if (MyGNotifier.Properties.Settings.Default.MAIN_CHECK_MONITOR)
            {
                DateTime dtFine = DateTime.Now;
                TimeSpan ts = dtFine - dtInizio;
                rtLog.Text += DateTime.Now.ToString() + "-> FINE CONTROLLO CASELLA POSTA: DURATA CONTROLLO " + ts.Seconds.ToString() + " secondi.\n";
            }
        }
Esempio n. 27
0
        public void MYG_IMAP_READ_AND_MARK(Imap4Client imap)
        {
            if (!bIMAP_ERROR)
            {
                nIcon.Icon = MyGNotifier.Properties.Resources.MyGNotify_Checking;
                try
                {
                    imap.Command("capability");

                    Mailbox inbox = imap.SelectMailbox("inbox");
                    int[] ids = inbox.Search("UNSEEN");
                    if (ids.Length > 0)
                    {
                        iCountIDS = 0;
                        for (var i = 0; i < ids.Length; i++)
                        {
                            if (!MSGS_ID.Contains(ids[i].ToString()))
                            {
                                iCountIDS++;
                                MSGS_ID.Add(ids[i].ToString());
                            }
                        }

                        if (iCountIDS > 0)
                        {
                            iLastCOUNT = iCountIDS;
                            MSGS_DETAILS = "";
                            nIcon.Icon = MyGNotifier.Properties.Resources.MyGNotify_Check;
                            bNewMsgICON = true;
                            NEW_MSGS = true;

                            //ActiveUp.Net.Mail.Message msg_first = inbox.Fetch.MessageObject(ids[0]);

                            //XElement xmail = new XElement("gmail",
                            //    new XAttribute("count", ids.Length.ToString()),
                            //    new XAttribute("modified", msg_first.Date.ToString())
                            //);

                            //string name = "", address = "", from = "";
                            //Regex reg_name = new Regex("\"[^\"]+");
                            //Regex reg_address = new Regex("<[^>]+");

                            ActiveUp.Net.Mail.Message msg = null;

                            for (var i = 0; i < ids.Length; i++)
                            {
                                msg = inbox.Fetch.MessageObject(ids[i]);

                                //from = msg.HeaderFields["from"];
                                //name = reg_name.Match(from).Value.Replace("\"", "");
                                //address = reg_address.Match(from).Value.Replace("<", "");

                                rtLog.Text += DateTime.Now.ToString() + "\n";
                                rtLog.Text += "DATA: " + msg.Date + "\n";
                                rtLog.Text += "MITTENTE: " + msg.From + "\n";
                                rtLog.Text += "OGGETTO: " + msg.Subject + "\n";
                                rtLog.Text += "----------------------------\n";

                                MSGS_DETAILS += "DATA: " + msg.Date + "\n";
                                MSGS_DETAILS += "MITTENTE: " + msg.From + "\n";
                                MSGS_DETAILS += "OGGETTO: " + msg.Subject + "\n";
                                MSGS_DETAILS += "---------------------------\n";

                                //xmail.Add(new XElement("entry",
                                //    new XAttribute("id", msg.MessageId),
                                //    new XAttribute("modified", msg.Date.ToString()),
                                //    new XAttribute("name", name),
                                //    new XAttribute("address", address),
                                //    new XElement("subject", msg.Subject),
                                //    new XElement("body-text", msg.BodyText.TextStripped),
                                //    new XElement("body-html", msg.BodyHtml.Text)
                                //));
                                //mark as unread
                                var flags = new FlagCollection();
                                flags.Add("Seen");
                                inbox.RemoveFlags(ids[i], flags);
                            }

                            //File.WriteAllText("gmail.xml", xmail.ToString());
                        }
                        else
                        {
                            NEW_MSGS = false;
                            nIcon.Icon = MyGNotifier.Properties.Resources.MyGNotify_Empty_Gray;
                        }
                    }
                    else
                    {
                        NEW_MSGS = false;
                        nIcon.Icon = MyGNotifier.Properties.Resources.MyGNotify_Empty_Gray;
                    }
                }
                catch (Exception err)
                {
                    nIcon.Icon = MyGNotifier.Properties.Resources.MyGNotify_Empty_Error;
                    rtError.Text += DateTime.Now.ToString() + "-> ERRORE CONNESSIONE IMAP:\n" + err.Message + "\n------------------\n"; ;
                    MGN_ERROR = DateTime.Now.ToString() + "-> ERRORE ELABORAZIONE IMAP: " + err.Message;
                    if (MGN_ERROR.ToLower().Contains("connessione interrotta"))
                    {
                        CONNECT_IMAP();
                    }
                    if (MyGNotifier.Properties.Settings.Default.MAIN_AUTO_NOTIFY_ERROR)
                    {
                        NOTIFY_ERROR(MGN_ERROR);
                    }
                }
            }
            else
            {
                rtLog.Text += "\n---------------\n" + DateTime.Now.ToString() + "-> ERRORE CONNESSIONE IMAP!\n---------------\n";
            }

            if (bNewMsgICON) { nIcon.Icon = MyGNotifier.Properties.Resources.MyGNotify_Check; }
        }
Esempio n. 28
0
    /// <summary>
    /// Connect the imap client.
    /// </summary>
    /// <param name="accountInfo">The information account</param>
    public void Connect(AccountSettings.AccountInfo accountInfo)
    {
        if (this._imap4Client == null || !this._imap4Client.IsConnected)
        {
            if (accountInfo != null && accountInfo.AccType == AccountType.POP3)
            {
                this._imap4Client = new Imap4Client();

                int port = accountInfo.PortIncomingServer;
                bool ssl = accountInfo.IsIncomeSecureConnection;
                string serverName = accountInfo.IncomingNameMailServer;
                string user = accountInfo.EmailAddress;
                string password = accountInfo.Password;
                bool useInPort = accountInfo.PortIncomingChecked;

                if (ssl)
                {
                    if (useInPort)
                    {
                        this._imap4Client.ConnectSsl(serverName, port);
                    }
                    else
                    {
                        this._imap4Client.ConnectSsl(serverName);
                    }
                }
                else
                {
                    if (useInPort)
                    {
                        this._imap4Client.Connect(serverName, port);
                    }
                    else
                    {
                        this._imap4Client.Connect(serverName);
                    }
                }

                this._imap4Client.Login(user, password);
            }
        }
    }
Esempio n. 29
0
 public void Verbinden()
 {
     _imap = new Imap4Client();
     _imap.Connect(_config["mailserver_receive"]);
     _imap.Login(_config["mailserver_user"], _config["mailserver_password"]);
 }
        // gets mailboxes, messages from wich we should get
        public static IEnumerable<ImapMailboxInfo> GetImapMailboxes(Imap4Client client, string server)
        {
            var mailboxes = new List<ImapMailboxInfo>();

            var special_domain_folders = new Dictionary<string, MailQueueItemSettings.MailboxInfo>();
            if (MailQueueItemSettings.SpecialDomainFolders.Keys.Contains(server))
                special_domain_folders = MailQueueItemSettings.SpecialDomainFolders[server];

            // get all mailboxes
            var response = client.Command("LIST \"\" \"*\"");
            var t = Regex.Split(response, "\r\n");
            for (var i = 0; i < t.Length - 2; i++)
            {
                var m = SysfolderRegex.Match(t[i]);
                if (!m.Success)
                    continue;

                var new_mailbox = new ImapMailboxInfo
                    {
                        folder_id = MailFolder.Ids.inbox,
                        name = m.Groups[3].Value,
                        tags = new string[]{}
                    };
                var separator = m.Groups[2].Value;
                if (new_mailbox.name.ToLower() != "inbox")
                {
                    var utf8_name = FolderNameDecodeHelper.Replace(new_mailbox.name, DecodeUtf7);
                    if (special_domain_folders.ContainsKey(utf8_name.ToLower()))
                    {
                        var info = special_domain_folders[utf8_name.ToLower()];
                        if (info.skip)
                            continue;

                        new_mailbox.folder_id = info.folder_id;
                    }
                    else
                    {
                        var look_for_parent = false;

                        var flags_match = ImapFlagRegex.Matches(m.Groups[1].Value.ToLower());
                        if (flags_match.Count > 0)
                        {
                            var matches = new List<string>();
                            for (var j = 0; j < flags_match.Count; j++)
                            {
                                matches.Add(flags_match[j].Groups[1].Value);
                            }

                            if (
                                matches.Any(
                                    @group =>
                                    MailQueueItemSettings.SkipImapFlags.Contains(
                                        @group.ToString(CultureInfo.InvariantCulture).ToLowerInvariant())))
                                continue;

                            var flag = MailQueueItemSettings.ImapFlags.FirstOrDefault(f => matches.Contains(f.Key));
                            if (null != flag.Key)
                            {
                                new_mailbox.folder_id = flag.Value;
                                // special case for inbox - gmail l10n issue
                                if (MailFolder.Ids.inbox == flag.Value && new_mailbox.name.ToLower() != "inbox")
                                    new_mailbox.name = "inbox";
                            }
                            else
                            {
                                look_for_parent = true;
                            }
                        }
                        else
                        {
                            look_for_parent = true;
                        }

                        if (look_for_parent)
                        {
                            // if mailbox is potentialy child - add tag. Tags looks like Tag1/Tag2/Tag3
                            const string tag_for_store_separator = "/";
                            var tag = utf8_name.Replace(separator, tag_for_store_separator);

                            var parent_index = GetParentFolderIndex(mailboxes, new_mailbox, separator);

                            if (parent_index >= 0)
                            {
                                var parent = mailboxes[parent_index];
                                new_mailbox.folder_id = parent.folder_id;

                                // if system mailbox - removes first tag
                                // if not system mailbox child - removes same count of tags as in parent
                                if (!parent.tags.Any())
                                    tag = tag.Substring(tag.IndexOf(tag_for_store_separator, StringComparison.Ordinal));
                            }

                            new_mailbox.tags = new[] { tag };
                        }
                    }
                }
                mailboxes.Add(new_mailbox);
            }

            return mailboxes;
        }