Example #1
0
 public void imapTest()
 {
     if (checkBox1.Checked)
     {
         addLog("Beginning SECURE IMAP test...");
     }
     else
     {
         addLog("Beginning IMAP test...");
     }
     using (ImapClient client = new ImapClient(serverBox.Text, Convert.ToInt32(portBox.Text), checkBox1.Checked, false))
     {
         if (client.Connect())
         {
             addLog("Connected to server!");
             addLog("Attempting to authenticate...");
             if (client.Login(userBox.Text, passBox.Text))
             {
                 addLog("Authentication successful!");
                 addLog("Test passed!");
             }
             else
             {
                 addLog("Authentication FAILED!");
                 addLog("Test FAILED!");
             }
         }
         else
         {
             addLog("Failed to connect to server!");
         }
     }
 }
        private void CheckImapMail()
        {
            try
            {
                using (ImapClient imapClient = new ImapClient(_configuration.ServerName, _configuration.Port, _configuration.SSL, null, _configuration.Encoding))
                {
                    imapClient.Login(_configuration.UserName, _configuration.Password, AuthMethod.Login);

                    IEnumerable <uint> uids = imapClient.Search(SearchCondition.Unseen());
                    foreach (MailMessage msg in uids.Select(uid => imapClient.GetMessage(uid)))
                    {
                        try
                        {
                            ProcessMail(msg);
                        }
                        catch (Exception ex)
                        {
                            Logger.Instance.LogException(this, ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Sometimes an error occures, e.g. if the network was disconected or a timeout occured.
                Logger.Instance.LogException(this, ex);
            }
        }
Example #3
0
        private void listBoxFolders_SelectedIndexChanged(object sender, EventArgs e)/////////////////////0000
        {
            var client = new ImapClient(ImapServerData.Server, ImapServerData.Port, ImapServerData.SSL);

            if (client.Connect())
            {
                if (client.Login(userLogin, userPassword))
                {
                    listBoxMessage.Items.Clear();

                    foreach (ImapX.Message m in client.Folders[listBoxFolders.SelectedIndex].Search("All", MessageFetchMode.Full))
                    {
                        listBoxMessage.Items.Add(string.Format("<- {0}  |||  {1}", m.From.DisplayName, m.Subject));
                    }
                }
                else
                {
                    MessageBox.Show("Проверьте правильность введенных данных");
                }
            }
            else
            {
                MessageBox.Show("Подключение не удалось, проверьте ваше интернет-соединение!");
            }
        }
Example #4
0
        private List<string> CheckForMessages()
        {
            var messages = new List<string>();

            _client = new ImapClient(_IMAPClientUri, true);
            if (_client.Connect() && _client.Login(_IMAPUsername, _IMAPPassword))
            {
                try
                {
                    var keyword = _subjectKeyword;                    
                    var emails = _client.Folders.Inbox.Search(string.Format("UNSEEN SUBJECT \"{0}\"", keyword), ImapX.Enums.MessageFetchMode.Full);
                    Console.WriteLine(string.Format("{0} emails", emails.Count()));
                    foreach (var email in emails)
                    {
                        messages.Add(email.Body.Text);
                        email.Remove();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                finally
                {
                    _client.Logout();
                    _client.Disconnect();                    
                }
            }
            else
            {
                Console.WriteLine("Bad email login");
            }
            return messages;
        }
Example #5
0
        public void autorization(string login, string pass)//авторизация
        {
            login = comboBoxAccounts.Text;
            //login = textBoxLogin.Text.ToString();
            pass = maskedTextBoxPass.Text.ToString();
            var client = new ImapClient(ImapServerData.Server, ImapServerData.Port, ImapServerData.SSL);

            if (client.Connect())
            {
                if (client.Login(login, pass))
                {
                    succesAutorization     = true;
                    labelAutorization.Text = "Авторизация прошла успешно";
                    userLogin    = login;
                    userPassword = pass;
                }
                else
                {
                    succesAutorization = false;
                    MessageBox.Show("Проверьте правильность введенных данных");
                }
            }
            else
            {
                // connection not successful
                MessageBox.Show("Подключение не удалось, проверьте ваше интернет-соединение!");
            }
        }
Example #6
0
        public bool Login(string mail, string password)
        {
            bool result = false;

            try
            {
                _imapClient.Login(mail, password);
                result = _imapClient.IsAuthenticated;
            }
            catch (Exception ex)
            {
                if (ex is ImapClientException || ex is IOException)
                {
                    throw;
                }
                if (ex.Message.Contains("MBR1236"))
                {
                    result = false;
                }
                else if (!ex.Message.Contains("Application-specific password required") && !ex.Message.Contains("Please log in via your web browser") && !ex.Message.Contains("profil.wp.pl"))
                {
                    result = false;
                }
                else
                {
                    result = false;
                }
            }
            return(result);
        }
Example #7
0
        private void buttonSendMessage_Click(object sender, EventArgs e) //событие отправки сообщения
        {
            var imapClient = new ImapClient(ImapServerData.Server, true);

            if (imapClient.Connect())
            {
                if (imapClient.Login(userLogin, userPassword))
                {
                    // Sending a message
                    var newMsg = SendMail(
                        SmtpServerData.Server,
                        userLogin,
                        userPassword,
                        userLogin,
                        textBoxToFriend.Text.ToString(),
                        textBoxSubject.Text.ToString(),
                        textBoxBody.Text.ToString()
                        );

                    // Uploading the sent message to the Sent folder
                    imapClient.Folders.Sent.AppendMessage(newMsg);
                    labelSendMessage.Text = "Сообщение успешно отправлено!";
                }
                else
                {
                    MessageBox.Show("Проверьте правильность введенных данных");
                }
            }
            else
            {
                MessageBox.Show("Подключение не удалось, проверьте ваше интернет-соединение!");
            }
        }
Example #8
0
        private void listBoxMessage_SelectedIndexChanged(object sender, EventArgs e)//загрузка в текстовое поле тело выбранного письма
        {
            var client   = new ImapClient(ImapServerData.Server, ImapServerData.Port, ImapServerData.SSL);
            int selIndex = listBoxMessage.SelectedIndex;


            if (client.Connect())
            {
                if (client.Login(userLogin, userPassword))
                {
                    ImapX.Message mess;
                    var           msg = client.Folders.Inbox.Search("ALL", MessageFetchMode.Full);
                    mess = msg[selIndex];
                    SaveManager.Saves.Messages.Add(new MailSave(mess.From.Address, mess.Subject, mess.Body.Text));
                    SaveManager.Save();
                    textBoxSeeBoby.Text = Encoding.Default.GetString(Encoding.Convert(Encoding.Default, Encoding.Default, Encoding.Default.GetBytes(mess.Body.Text)));
                }
                else
                {
                    MessageBox.Show("Проверьте правильность введенных данных");
                }
            }
            else
            {
                MessageBox.Show("Подключение не удалось, проверьте ваше интернет-соединение!");
            }
        }
Example #9
0
        private void button2_Click(object sender, EventArgs e)
        {
            UpdateTargetServerSettings();

            using (ImapClient client = new ImapClient(targetServerSettings.Hostname, targetServerSettings.Port, targetServerSettings.UseSSL))
            {
                if (client != null)
                {
                    if (!client.IsConnected)
                    {
                        client.Connect();
                    }

                    if (client.Login(targetServerSettings.Username, targetServerSettings.Password))
                    {
                        client.Logout();
                        client.Disconnect();

                        MessageBox.Show("Connection succesful.");
                    }
                    else
                    {
                        MessageBox.Show("Username or password is incorrect, could not login");
                    }
                }
                else
                {
                    MessageBox.Show("Failed to connect to host, please check hostname, port and SSL option");
                }
            }
        }
Example #10
0
        private List <string> CheckForMessages()
        {
            var messages = new List <string>();

            _client = new ImapClient(_IMAPClientUri, true);
            if (_client.Connect() && _client.Login(_IMAPUsername, _IMAPPassword))
            {
                try
                {
                    var keyword = _subjectKeyword;
                    var emails  = _client.Folders.Inbox.Search(string.Format("UNSEEN SUBJECT \"{0}\"", keyword), ImapX.Enums.MessageFetchMode.Full);
                    Console.WriteLine(string.Format("{0} emails", emails.Count()));
                    foreach (var email in emails)
                    {
                        messages.Add(email.Body.Text);
                        email.Remove();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                finally
                {
                    _client.Logout();
                    _client.Disconnect();
                }
            }
            else
            {
                Console.WriteLine("Bad email login");
            }
            return(messages);
        }
Example #11
0
        private bool connect(ImapClient client)
        {
            bool success = false;

            // basic setings (required)
            client.Host     = serverAddress;
            client.Username = emailAccount;
            client.Password = emailPassword;
            client.Port     = port;

            if (SSL == "Yes")
            {
                // Settings required for SSL enabled Imap servers
                client.SecurityMode = ImapSslSecurityMode.Implicit;
                client.EnableSsl    = true;
            }

            try
            {
                client.Connect();
                client.Login();
                success = true;
            }
            catch (Exception e)
            {
                Utils.WriteToLog(Utils.LogSeverity.Error, processName, "The following error was generated whilst trying to connect: (IMAP)" + e.InnerException + "\n" + e.Message + "\n" + e.StackTrace);
            }

            return(success);
        }
Example #12
0
        /// <summary>
        /// Searches using an S22 Imap client
        /// </summary>
        /// <param name="searchCriteria"></param>
        /// <param name="processMessages"></param>
        /// <returns></returns>
        public IEnumerable <IEmail> Search(EmailSearchCriteria searchCriteria, bool processMessages = true)
        {
            // create client
            var imapClient = new ImapClient(_host, _port, _useSsl);

            // log in
            imapClient.Login(_userName, _password, AuthMethod.Auto);

            // search for messages
            var messageIds = imapClient.Search(GetSearchCondition(searchCriteria), searchCriteria.Folder);

            // no messages found - return empty collection
            if (messageIds == null || messageIds.Length == 0)
            {
                return(new List <IEmail>());
            }

            // get messages
            var messages = imapClient.GetMessages(messageIds, FetchOptions.TextOnly, true, searchCriteria.Folder);

            // check if messages downloaded properly
            if (messages == null || messages.Length == 0)
            {
                throw new ImapMessageDownloadException(_host, _port, _userName, searchCriteria.Folder, messageIds);
            }

            // create as S22ImapMessages
            return(messages.Select(m => new S22ImapMessage(m)));
        }
        public override int GetValue(String username, String password, String server, int port, Boolean useSsl)
        {
            var client = new ImapClient(server, port, useSsl ? SslProtocols.Default : SslProtocols.None, false);

            log.DebugFormat("Connecting to {0}:{1} SSL:{2}", server, port, useSsl);
            if (client.Connect())
            {
                log.DebugFormat("Logging in with {0}", username);

                if (client.Login(username, password))
                {
                    var messages = client.Folders.Inbox.Search("UNSEEN");

                    return(messages.Length);
                }
                else
                {
                    throw new Exception("Log in error");
                }
            }
            else
            {
                throw new Exception("Connection error");
            }
        }
Example #14
0
        private void tryLogin()
        {
            var cl = new ImapClient("imap.ukr.net", true, false);

            cl.Host = "imap.ukr.net";
            cl.Port = 993;
            try
            {
                if (cl.Connect())
                {
                    if (cl.Login(From, Password))
                    {
                        RaiseLogged();
                        return;
                    }
                    RaiseLoggingFailed();
                    return;
                }
                RaiseLoggingFailed();
            }
            catch (Exception)
            {
                RaiseLoggingFailed();
            }
        }
Example #15
0
 private int Test()
 {
     if (string.IsNullOrWhiteSpace(txtServer.Text))
     {
         MessageBox.Show("Please enter a server");
     }
     else if (string.IsNullOrWhiteSpace(txtPort.Text))
     {
         MessageBox.Show("Please enter a port");
     }
     else if (string.IsNullOrWhiteSpace(txtLogin.Text))
     {
         MessageBox.Show("Please enter a login");
     }
     else if (string.IsNullOrWhiteSpace(txtPassword.Password))
     {
         MessageBox.Show("Please enter a password");
     }
     else if (!_client.Connect(txtServer.Text, int.Parse(txtPort.Text), chkSSL.IsChecked.HasValue && chkSSL.IsChecked.Value, false))
     {
         MessageBox.Show("Failed to establish connection");
     }
     else if (!_client.Login(txtLogin.Text, txtPassword.Password))
     {
         MessageBox.Show("Invalid credentials");
     }
     else
     {
         // Do not download message data, only UIds to provide faster result
         _client.Behavior.MessageFetchMode = MessageFetchMode.None;
         var msgs = _client.Folders.All.Search();
         return(msgs.Length);
     }
     return(0);
 }
Example #16
0
        private void buttonLoadMessage_Click(object sender, EventArgs e)//загрузка списка сообщений
        {
            var client = new ImapClient(ImapServerData.Server, ImapServerData.Port, ImapServerData.SSL);

            listBoxMessage.Items.Clear();

            if (client.Connect())
            {
                if (client.Login(userLogin, userPassword))
                {
                    foreach (ImapX.Message m in client.Folders["INBOX"].Search("All", MessageFetchMode.Full))
                    {
                        listBoxMessage.Items.Add(string.Format("{0}({1})||| {2}", m.From.Address, m.From.DisplayName, m.Subject));
                    }
                }
                else
                {
                    MessageBox.Show("Проверьте правильность введенных данных");
                }
            }
            else
            {
                MessageBox.Show("Подключение не удалось, проверьте ваше интернет-соединение!");
            }
        }
Example #17
0
        public static ImapX.ImapClient Login(string str_email, string str_password)
        {
            ImapX.ImapClient client = new ImapClient("imap.gmail.com", true);

            string correct = "";
            string host    = "";
            bool   flag    = false;

            for (int i = 0; i < str_email.Length; i++)
            {
                if (str_email[i] != ' ')
                {
                    correct += str_email[i];
                }
            }

            for (int i = 0; i < correct.Length; i++)
            {
                if (correct[i] == '@' || flag)
                {
                    if (flag)
                    {
                        host += correct[i];
                    }
                    flag = true;
                }
            }
            if (correct == "" || str_password == "")
            {
                MessageBox.Show("Wrong username or password");
            }
            else if (host != "")
            {
                str_email       = correct;
                MyInfo.userName = str_email;
                MyInfo.password = str_password;
                MyInfo.host     = host;
                host            = "imap." + host;
                //client = new ImapClient(host, true);
                if (client.Connect())
                {
                    if (client.Login(str_email, str_password))
                    {
                        MyInfo.isconnected = true;
                    }
                }
                else
                {
                    MessageBox.Show("Error in connection");
                    // connection not successful
                }
            }
            else
            {
                MessageBox.Show("Missing server name");
            }

            return(client);
        }
 internal bool GmailAuthenticate(string username, string password)
 {
     var client = new ImapClient("imap.gmail.com", 993, true, true);
     client.Connect();
     bool result = client.Login(username,password);
     if (result) return true;
     else return false;
 }
Example #19
0
 public MailClient()
 {
     try
     {
         client.Login(Program.config["MailUsername"], Program.config["MailPassword"], AuthMethod.Auto);
     }
     catch { }
     if (!client.Authed)
     {
         Logger.Error(PREFIX + "Can't log in to mail server.");
         Program.Pause();
     }
     else
     {
         new Thread(new ThreadStart(() =>
         {
             while (true)
             {
                 try
                 {
                     var mails = client.Search(SearchCondition.Undeleted().And(SearchCondition.Unflagged()).And(SearchCondition.Unseen()).And(SearchCondition.From("*****@*****.**")));
                     foreach (uint id in mails)
                     {
                         processMessage(id);
                     }
                     Thread.Sleep(500);
                 }
                 catch
                 {
                     if (!client.Authed)
                     {
                         try
                         {
                             client.Login(Program.config["MailUsername"], Program.config["MailPassword"], AuthMethod.Auto);
                         }
                         catch { }
                     }
                 }
             }
         }))
         {
             IsBackground = true
         }.Start();
         Logger.Info(PREFIX + "Successfully logged in to mail server.");
     }
 }
Example #20
0
        public ActionResult ProviderAnswers()
        {
            try
            {
                //Create imap client
                var client = new ImapClient();

                client.Port        = 993;
                client.SslProtocol = SslProtocols.Default;
                client.Host        = "imap-mail.outlook.com";
                client.ValidateServerCertificate = true;
                client.UseSsl = true;

                var viewModel = new List <EmailViewModel>();

                //Connect
                if (client.Connect())
                {
                    var organisation = this.organisationService.GetById(
                        this.userService.GetUserOrganisationId(this.User.Identity.GetUserId()));

                    var sentFrom = organisation.EmailClient;
                    var pwd      = KAssets.Controllers.StaticFunctions.RSAALg.Decryption(organisation.EmailClientPassword);

                    //Login
                    if (client.Login(sentFrom, pwd))
                    {
                        //Download the messages
                        client.Folders.Inbox.Messages.Download();
                        MessageCollection messages = client.Folders.Inbox.Messages;

                        //Add messages to viewmodel
                        foreach (var mess in messages)
                        {
                            viewModel.Add(new EmailViewModel
                            {
                                DateOfSend = mess.Date.Value.ToString(),
                                From       = mess.From.Address,
                                Seen       = mess.Seen,
                                Subject    = mess.Subject,
                                UId        = mess.UId
                            });
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Connection Failed. Please refresh");
                }

                client.Disconnect();
                return(View(viewModel));
            }
            catch
            {
                return(Redirect("/Orders/ProviderOrder/ProviderAnswers"));
            }
        }
Example #21
0
        private void LoginImap()
        {
            var username = currentUser.EmailAdress;

            byte[] plainText = ProtectedData.Unprotect(currentUser.EncodingText, currentUser.Entropy, DataProtectionScope.CurrentUser);
            var    password  = Encoding.UTF8.GetString(plainText).ToString();

            imapClient.Login(username, password, AuthMethod.Login);
        }
Example #22
0
        public void SetSeen(List <Message> messages)
        {
            bool   connected = false;
            string username  = Email;
            string password  = Password;
            int    port      = ImapPort;
            bool   useSSL    = ImapSSL;

            try
            {
                if (ImapClient == null)
                {
                    ImapClient = new ImapX.ImapClient(ImapServer, ImapPort, ImapSSL);
                }

                if (!ImapClient.IsConnected)
                {
                    ImapClient.Connect();
                }

                if (ImapClient.IsConnected)
                {
                    if (!ImapClient.IsAuthenticated)
                    {
                        ImapClient.Login(Email, Password);
                    }
                    if (ImapClient.IsAuthenticated)
                    {
                        connected = true;
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error("Не удалось установить соединение и авторизоваться на сервере " + (ImapServer ?? "") + ".\r\nУдаленный порт: " + ImapPort + "\r\nШифрование:" + (ImapSSL ? "Включено" : "Выключено") + "\r\nТекст ошибки:", e);

                connected = false;
            }
            if (connected)
            {
                try
                {
                    var folder = ImapClient.Folders.Inbox;
                    foreach (var message in messages)
                    {
                        message.Seen = true;
                        message.Remove();
                    }
                }
                catch (Exception e)
                {
                    logger.Error("Ошибка при  отметке о чтении писем на почтовом ящике " + (Email ?? "") + ".\r\nАдрес сервера:" + (ImapServer ?? "") + ".\r\nУдаленный порт: " + ImapPort + "\r\nШифрование:" + (ImapSSL ? "Включено" : "Выключено") + "\r\nТекст ошибки:", e);
                }
            }
            ImapClient = null;
        }
 /// <summary>
 /// Connects to the imap server.
 /// </summary>
 /// <param name="login">Login credidentials containing username and password of user</param>
 /// <param name="server">Server address to connect to</param>
 public void Connect(LoginCred login, string server)
 {
     imapc = new ImapClient(server, true);
       if (imapc.Connect())
     if (imapc.Login(login.Username, login.Password))
     {
       blnConnected = true;
       imapc.Behavior.AutoPopulateFolderMessages = true;
     }
 }
Example #24
0
        //http://imapx.codeplex.com/documentation

        static void Main(string[] args)
        {
            // ApplicationTrustPolicy.TrustAll();

            string credientials = ConfigurationManager.AppSettings["credentials"];
            string imap_server  = ConfigurationManager.AppSettings["imap_server"];
            string logfilename  = ConfigurationManager.AppSettings["log"];
            string output_dir   = ConfigurationManager.AppSettings["output_dir"];
            string email_folder = ConfigurationManager.AppSettings["email_folder"];


            var client = new ImapClient(imap_server, true, false);

            if (logfilename != null)
            {
                Logger.EnableLogger();
                Logger.WriteLine("logging to '" + logfilename + "'");
                Debug.Listeners.Add(new TextWriterTraceListener(logfilename));
                Debug.AutoFlush = true;
                client.IsDebug  = true;
            }

            var files = Directory.GetFiles(credientials, "*.*");
            var user  = Path.GetFileName(files[0]);
            var pass  = File.ReadAllLines(files[0])[0];

            Logger.WriteLine("about to connect:");
            if (client.Connect())
            {
                if (client.Login(user, pass))
                {
                    // login successful
                    Console.WriteLine("ok");
                    Logger.WriteLine("listing labels...");
                    foreach (var item in client.Folders)
                    {
                        Logger.WriteLine(item.Name);
                    }

                    var folder = client.Folders[email_folder];
                    folder.Messages.Download("UNSEEN", MessageFetchMode.Basic | MessageFetchMode.GMailExtendedData, 72);
                    var s     = GetSerieData(folder);
                    var cbtt  = "mpci";
                    var pcode = "qp2";

                    string fn = "instant_" + cbtt + "_" + pcode + "_" + DateTime.Now.ToString("MMMdyyyyHHmmssfff") + ".txt";
                    fn = Path.Combine(output_dir, fn);
                    HydrometInstantSeries.WriteToHydrometFile(s, cbtt, pcode, "hydromet", fn);
                }
            }
            else
            {
                Logger.WriteLine("connection not successful");
            }
        }
Example #25
0
 public static bool AuthenticateClient(ImapClient client, string username, string password)
 {
     try
     {
         return(client.Login(username, password));
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
Example #26
0
        public static void Verify(string email, string pass, string ipmap, int port)
        {
            string url = null;

            using (ImapClient ic = new ImapClient())
            {
                ic.Connect(ipmap, port, true, false);
                ic.Login(email, pass);
                ic.SelectMailbox("INBOX");
                int mailcount;
                for (mailcount = ic.GetMessageCount(); mailcount < 2; mailcount = ic.GetMessageCount())
                {
                    Mail.Delay(5);
                    ic.SelectMailbox("INBOX");
                }
                MailMessage[] mm    = ic.GetMessages(mailcount - 1, mailcount - 1, false, false);
                MailMessage[] array = mm;
                for (int j = 0; j < array.Length; j++)
                {
                    MailMessage i = array[j];
                    //bool flag = i.Subject == "Account registration confirmation" || i.Subject.Contains("Please verify your account");
                    //if (flag)
                    {
                        string sbody = i.Body;
                        url = Regex.Match(i.Body, "a href=\"(https:[^\n]+)").Groups[1].Value;
                        bool flag2 = string.IsNullOrEmpty(url);
                        if (flag2)
                        {
                            url = Regex.Match(i.Body, "(http.*)").Groups[1].Value.Trim();
                            url = url.Substring(0, url.IndexOf('"'));
                        }
                        break;
                    }
                }
                ic.Dispose();
            }
            HttpRequest rq = new HttpRequest();

            rq.Cookies   = new CookieDictionary(false);
            rq.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36";
            bool Load = false;

            while (!Load)
            {
                try
                {
                    rq.Get(url, null);
                    Load = true;
                }
                catch (Exception)
                {
                }
            }
        }
Example #27
0
        //http://imapx.codeplex.com/documentation
        static void Main(string[] args)
        {
            // ApplicationTrustPolicy.TrustAll();

            string credientials = ConfigurationManager.AppSettings["credentials"];
            string imap_server = ConfigurationManager.AppSettings["imap_server"];
            string logfilename = ConfigurationManager.AppSettings["log"];
            string output_dir = ConfigurationManager.AppSettings["output_dir"];
            string email_folder = ConfigurationManager.AppSettings["email_folder"];

            var client = new ImapClient(imap_server, true,false);

            if (logfilename != null)
            {
                Logger.EnableLogger();
                Logger.WriteLine("logging to '" + logfilename + "'");
                Debug.Listeners.Add(new TextWriterTraceListener(logfilename));
                Debug.AutoFlush = true;
                client.IsDebug = true;
            }

            var files = Directory.GetFiles(credientials, "*.*");
            var user =  Path.GetFileName(files[0]);
            var pass = File.ReadAllLines(files[0])[0];
            Logger.WriteLine("about to connect:");
            if (client.Connect())
            {

                if (client.Login(user,pass))
                {
                    // login successful
                    Console.WriteLine("ok");
                    Logger.WriteLine("listing labels...");
                    foreach (var item in client.Folders)
                    {
                        Logger.WriteLine(item.Name);
                    }

                    var folder = client.Folders[email_folder];
                   folder.Messages.Download("UNSEEN", MessageFetchMode.Basic | MessageFetchMode.GMailExtendedData, 72);
                   var s = GetSerieData(folder);
                    var cbtt = "mpci";
                    var pcode="qp2";

                    string fn = "instant_" + cbtt + "_" + pcode + "_" + DateTime.Now.ToString("MMMdyyyyHHmmssfff") + ".txt";
                    fn = Path.Combine(output_dir, fn);
                   HydrometInstantSeries.WriteToHydrometFile(s, cbtt, pcode, "hydromet", fn);
                }
            }
            else
            {
                Logger.WriteLine("connection not successful");
            }
        }
        /// <summary>
        /// receive emails from IMAP
        /// </summary>
        public static List <EmailMessageModel> ReceiveEmailsFromIMAP(ServiceSettingsModel model)
        {
            try
            {
                List <EmailMessageModel> models = new List <EmailMessageModel>();
                var client = new ImapClient(model.ImapSettings.Server, model.ImapSettings.Port, model.ImapSettings.UseSSL);
                if (client.Connect())
                {
                    if (client.Login(model.Credentials.UserName, model.Credentials.Password))
                    {
                        // login successful

                        List <string> lst = new List <string>();

                        foreach (var folder in client.Folders)
                        {
                            lst.Add(folder.Name);

                            if (folder.Name.ToLower().Equals(model.ImapSettings.DefaultFolder.ToLower()))
                            {
                                folder.Messages.Download("ALL", MessageFetchMode.Full, Int32.MaxValue);

                                foreach (var message in folder.Messages)
                                {
                                    if (!message.Seen)
                                    {
                                        models.Add(new EmailMessageModel()
                                        {
                                            Body          = message.Body.Text,
                                            DateTime      = message.Date,
                                            ReceiverEmail = model.Credentials.UserName,
                                            SenderEmail   = message.From.Address,
                                            Subject       = message.Subject
                                        });

                                        //message.Seen = true;
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    return(null);
                }
                return(models);
            }
            catch (Exception)
            {
                return(null);
            }
        }
        public bool Connect()
        {
            if (_client.Connect())
            {
                if (_client.Login(_address, _password))
                {
                    return(true);
                }
            }

            return(false);
        }
Example #30
0
        public MailState CheckMailbox()
        {
            try
            {
                bool connOk = _client.Connect();
                if (!connOk)
                {
                    return(MailState.Unknown);
                }

                bool credOk = _client.Login();
                if (!credOk)
                {
                    return(MailState.InvalidCredentials);
                }

                try
                {
                    var newMessages = new HashSet <MailMessage>();

                    foreach (var folder in _client.Folders)
                    {
                        if (folder.Selectable)
                        {
                            var unreadMessages = folder.Search("UNSEEN");

                            foreach (var message in unreadMessages)
                            {
                                string from = string.IsNullOrEmpty(message.From.DisplayName) ? message.From.Address : message.From.DisplayName;
                                newMessages.Add(new MailMessage(from, message.Subject));
                            }
                        }
                    }

                    NewMessages.Clear();
                    foreach (var message in newMessages)
                    {
                        NewMessages.Add(message);
                    }

                    return(NewMessages.Count == 0 ? MailState.NoNewMail : MailState.NewMail);
                }
                catch
                {
                    return(MailState.Unknown);
                }
            }
            finally
            {
                _client.Disconnect();
            }
        }
Example #31
0
        private void StartMonitorigThread()
        {
            if (string.IsNullOrEmpty(Settings.Default.ImapSrv) || string.IsNullOrEmpty(Settings.Default.ImapUser) || string.IsNullOrEmpty(Settings.Default.ImapPwd))
            {
                _notifyIcon.ShowBalloonTip(1000, "Помилка", "Перевірте налаштування.", ToolTipIcon.Error);
            }
            else
            {
                try
                {
                    if (_imapClient != null)
                    {
                        _imapClient.Logout();
                        _imapClient.Disconnect();
                        _imapClient.Folders.Inbox.OnNewMessagesArrived -= Inbox_OnNewMessagesArrived;
                        _imapClient.Dispose();
                    }

                    _imapClient = new ImapClient(Settings.Default.ImapSrv, (int)Settings.Default.SslPort, true);

                    if (_imapClient.Connect())
                    {
                        if (_imapClient.Login(Settings.Default.ImapUser, Settings.Default.ImapPwd))
                        {
                            _messageProcessor = new MessageProcessor(_appEntitiesRepo, Settings.Default.FlatNumberRegex, Settings.Default.MeterReadingRegex);

                            _imapClient.Folders.Inbox.OnNewMessagesArrived += Inbox_OnNewMessagesArrived;
                            if (_imapClient.Folders.Inbox.StartIdling())
                            {
                                _notifyIcon.ShowBalloonTip(1000, string.Empty, "Чекаю на нові листи...", ToolTipIcon.Info);
                            }
                            else
                            {
                                _notifyIcon.ShowBalloonTip(1000, "Помилка", "Неможу почати слухати папку Inbox", ToolTipIcon.Error);
                            }
                        }
                        else
                        {
                            _notifyIcon.ShowBalloonTip(1000, "Помилка", "Перевірте логін та пароль!", ToolTipIcon.Error);
                        }
                    }
                    else
                    {
                        _notifyIcon.ShowBalloonTip(1000, "Помилка", "З'єднання невдале.", ToolTipIcon.Error);
                    }
                }
                catch (Exception exception)
                {
                    _notifyIcon.ShowBalloonTip(1000, "Помилка", exception.Message, ToolTipIcon.Error);
                }
            }
        }
Example #32
0
 private void frmMailList_Load(object sender, EventArgs e)
 {
     // https://support.google.com/mail/thread/21528208?hl=en
     _ImapClient = new ImapClient(_serverName, _sererPort, System.Security.Authentication.SslProtocols.Tls, true);
     if (_ImapClient.Connect())
     {
         if (_ImapClient.Login(_login, _password))
         {
             GetNodesFromFolders(_ImapClient.Folders, null);
             tlFolders.FocusedNode = tlFolders.Nodes.FirstNode;
         }
     }
 }
Example #33
0
 public MessageReader(string host, int port, bool enableSsl, string email, string password)
 {
     try
     {
         _imapClient = new ImapClient(host, port, enableSsl);
         _imapClient.Login(email, password, AuthMethod.Login);
     }
     catch (Exception ex)
     {
         _logger.Log(LogLevel.Error, "Ошибка при авторизации по IMAP: " + ex.ToString());
         throw ex;
     }
 }
Example #34
0
        private static bool Connect(ImapClient client)
        {
            if (client.Connect())
            {
                //if (client.Login(MailLogin, MailPassword))
                if (client.Login("*****@*****.**", "1597534682"))
                {
                    return true;
                }
            }

            return false;
        }
        public EmailRepository(EmailRepositoryArguments _arguments)
        {
            arguments = _arguments;
            Name      = _arguments.Name;

            client = new ImapClient(arguments.HostName, arguments.Port, arguments.UseSsl);
            client.Connect();

            if (!client.Login(_arguments.Username, _arguments.Password))
            {
                throw new RepositoryConfigurationException(ConfigurationExceptionCategory.InvalidCredentials, this, "Failed to Connect to " + Name);
            }
        }
Example #36
0
 /// <summary>
 /// Initializes the ImapClient with the given server, account & password
 /// </summary>
 /// <param name="imap">Imap server to use</param>
 /// <param name="account">E-mail account</param>
 /// <param name="password">Password</param>
 /// <returns>True if connection was successful</returns>
 public bool InitializeImapClient(string imap, string account, string password)
 {
     client = new ImapClient(imap, true, false);
     if (client.Connect())
     {
         if (client.Login(account, password))
         {
             return true;
         }
         return false;
     }
     else
     {
         return false;
     }
 }
 internal async Task<List<MailItem>> GetEmailMessages(string user,string pass,int pageNo, int pageSize)
 {
     List<MailItem> returnResults = new List<MailItem>();
     var client = new ImapClient("imap.gmail.com", 993,true, true);
     client.Connect();
     client.Login(user,pass);
     var messages = client.Folders["INBOX"].Search("ALL",ImapX.Enums.MessageFetchMode.Basic| ImapX.Enums.MessageFetchMode.Flags, pageSize);
     foreach (ImapX.Message msg in messages)
     {
         MailItem item = new MailItem();
         item.Sender = msg.From.ToString();
         item.Body = msg.Body.Text;
         item.Subject = msg.Subject;
         item.Received = msg.Date;
         
         returnResults.Add(item);
         
     }
     return returnResults;
 }
Example #38
0
        public void DownloadEmailAttachment()
        {
            ImapClient imapClient = new ImapClient(host);

            imapClient.IsDebug = true;

            if (imapClient.Connect())
            {
                Console.WriteLine("Connect to {0} OK", host);
            }
            else
            {
                Console.WriteLine("Connect to {0} FAILED", host);
                Console.ReadKey();
                return;
            }


            if (imapClient.Login(this.EmailAccount, this.password))
            {
                Console.WriteLine("Login OK");
            }
            else
            {
                Console.ReadKey();
                return;
            }

            Folder testFolder = imapClient.Folders["其他文件夹"].SubFolders["比利时"];

            testFolder.Messages.Download("ALL", ImapX.Enums.MessageFetchMode.Full);

            Console.WriteLine("Messages downloaded! Messages count:{0}", testFolder.Messages.Count());


            List<Message> list = new List<Message>();

            foreach (var message in testFolder.Messages)
            {
                Console.WriteLine("===Message Start===");

                Console.WriteLine("Message Title : {0}", message.Subject);

                Console.WriteLine("Message Header : {0}", string.Join(",", message.Headers.Select(x => x.Key + "->" + x.Value)));

                Console.WriteLine("Message Body : ");

                Console.WriteLine(message.Body.Text);

                Console.WriteLine("Message Attachments");

                foreach (var file in message.Attachments)
                {
                    Console.WriteLine(file.FileName);
                    Console.WriteLine(file.FileSize);
                    Console.WriteLine("--");

                    file.Save(@"T:\");
                }


                Console.WriteLine("===Message End===");

                list.Add(message);
            }


            foreach (var message in list)
            {
                if (message.MoveTo(imapClient.Folders["其他文件夹"].SubFolders["比利时完成"]))
                {
                    Console.WriteLine("Message moved OK");
                }
                else
                {
                    Console.WriteLine("Message moved FAILED");
                }
            }

            var keyInfo = Console.ReadKey(true);


            


            imapClient.Logout();
        }
Example #39
0
        static void Main(string[] args)
        {
            //Если существует файл с настройками
            if (File.Exists("settings.json"))
            {
                //Считываем файл настроек
                string settings_file = File.ReadAllText("settings.json");

                //Создаем объект типа jobject
                JObject settings = JObject.Parse(settings_file);

                //Создадим объект класса ImapX
                var client = new ImapClient(settings["IMAP"].ToString(), Convert.ToInt32(settings["Port"]), true);
                
                //Объявляем регулярное выражение для поиска нужной ссылки
                var find_url = new Regex("style=\"background:#799905;\"><a href=\"(.*)\"> <span style=\"border-radius:2px;");

                //Проверим успешно ли подключились
                if (client.Connect())
                {
                    //Выводим информацию в консоль, что подключились
                    Console.WriteLine("Successfully connected");

                    //Пробуем войти в почтовый ящик
                    if (client.Login(settings["Mail"].ToString(), settings["Password"].ToString()))
                    {
                        //Пишем в консоль, что вошли успешно
                        Console.WriteLine("Login successfully");

                        //Теперь будем постоянно обновлять нашу почту - раз в N секунд
                        while (true)
                        {
                            //Выведем в консоль что пошла новая проверка
                            Console.WriteLine("{0} - Checking mailbox...", DateTime.Now);

                            //Пробежимся по всем непрочитанным письмам
                            foreach (var mess in client.Folders["INBOX"].Search("UNSEEN"))
                            {
                                //Если это сообщение от стима
                                if (mess.Subject == "Steam Trade Confirmation")
                                {
                                    //Пробуем найти ссылку
                                    try
                                    {
                                        //Выводим сообщение, что нашли новое письмо
                                        Console.WriteLine("Find new unred message from " + mess.From);

                                        //Найдем совпадения
                                        Match match = find_url.Match(mess.Body.Html.ToString());

                                        //Преобразуем ссылку в правильный формат
                                        string url = match.Groups[1].Value.Replace("&amp;", "&");

                                        //Если проверим нашло ли вообще ссылку
                                        if (String.IsNullOrEmpty(url))
                                        {
                                            //Отправим подтверждение
                                            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                                            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                                        }
                                    }
                                    catch(Exception e)
                                    {
                                        Console.Write("Url was not found");
                                    }

                                    //Отметим письмо как прочитанное
                                    mess.Seen = true;
                                }
                            }

                            //Поставим паузу на нужное количесво сепкунд
                            Thread.Sleep(Convert.ToInt32(settings["UpdateTime"]) * 1000);
                        }
                    }
                    else
                        Console.WriteLine("Bad login/password");
                }
                else
                    Console.WriteLine("Connection error");
            }
        }
        public List<Email> GetMail()
        {
            string getAllMail = Config["GetMailType"].Equals("GETALLMAIL123") ? "ALL" : "UNSEEN";
            MessageCollection remoteEmails;
            List<Email> emails = new List<Email>();
            ImapClient imapClient = new ImapClient(Config["Host_Google"], true, false);
            bool imapConnected = false;
            bool imapLoggedIn = false;

            try
            {
                imapConnected = imapClient.Connect();
                imapLoggedIn = imapClient.Login(Config["User_Google"], Config["Password_Google"]);
                CurrentMailAccessIndicator = MailAccessIndicator.LoggedIn;
            }
            catch (Exception e)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Log(LogLevel.Error, "Connection to Google Mail server cannot be established.", e);
            }

            if (imapConnected && imapLoggedIn)
            {
                // Get messages from remote source
                ImapX.Folder InboxFolder = imapClient.Folders.Inbox;
                remoteEmails = InboxFolder.Messages;
                remoteEmails.Download(getAllMail);
                CurrentMailAccessIndicator = MailAccessIndicator.MailChecked;
                
                foreach (Message remoteEmail in remoteEmails)
                {
                    try
                    {
                        Email email = new Email
                        {
                            Date = remoteEmail.Date,
                            From = remoteEmail.From.Address.ToString(),
                            Subject = remoteEmail.Subject,
                            Body = remoteEmail.Body.Text
                        };

                        if (remoteEmail.Attachments.Length > 0)
                        {
                            email.Attachments = new List<Domain.Attachment>();

                            foreach (ImapX.Attachment anAttachment in remoteEmail.Attachments)
                            {
                                anAttachment.Download();
                                string attachmentFileName = DateTime.Now.ToString("yyyyMMddHHMMss.f") + anAttachment.FileName;
                                email.Attachments.Add(
                                    new Domain.Attachment {
                                        FileName = attachmentFileName,
                                        Content = anAttachment.FileData
                                    });
                            }
                        }
                        remoteEmail.Seen = Config["MarkAsSeen"].ToString().Equals("True") ? true : false;
                        emails.Add(email);
                    }
                    catch (Exception e)
                    {
                        Logger logger = LogManager.GetCurrentClassLogger();
                        logger.Log(LogLevel.Error, "Exception occurred when saving emails", e);
                        CurrentMailAccessIndicator = MailAccessIndicator.MailFetchError;

                    }
                    CurrentMailAccessIndicator = MailAccessIndicator.MailFetched;
                }
            }

            imapClient.Dispose();

            TimeLastChecked = DateTime.Now;
            return emails;
        }
Example #41
0
        public void Check_ForUnseenMails()
        {
            try
            {
                //Connect
                Status = MainForm.myIni.Get_LanguageValue("messages", "connect_to").Replace("%1", Host);
                ImapClient myImapClient = new ImapClient(Host, Port, Username, Password, UseSsl, !UseSsl, ImapClient.AuthMethods.Login);
                try
                {
                    myImapClient.Connect();
                }
                catch
                {
                    Status = MainForm.myIni.Get_LanguageValue("messages", "host_unavailable").Replace("%1", Host);
                    return;
                }

                //Login
                try
                {
                    myImapClient.Login();
                }
                catch
                {
                    Status = MainForm.myIni.Get_LanguageValue("messages", "login_failed").Replace("%1", Host);
                    return;
                }

                //Retrieve unseen messages
                Status = MainForm.myIni.Get_LanguageValue("messages", "checking_mails").Replace("%1", Email);
                UnseenMessages = new List<UnseenMessage>();
                List<MailMessage> myMessages = Fetch_UnseenMails(myImapClient);
                foreach (MailMessage message in myMessages)
                {
                    string from_display_name = Examine_FromDisplayName(message);
                    string subject = message.Subject;
                    string body = Examine_Body(message);

                    UnseenMessages.Add(new UnseenMessage(message.MessageID, from_display_name, subject, body, message.Attachments.Count, message.Date));
                }

                Status = "";
                Finished = true;
            }
            catch (Exception e)
            {
                Status = e.Message;
            }
        }
Example #42
0
        private void GetFolders()
        {
            this.Cursor = Cursors.WaitCursor;

            Account account = accounts[iTalk_TabControl.SelectedIndex];

            try
            {
                _client.Logout();
                Console.WriteLine("Logout succeeded!");
            }
            catch
            {
                Console.WriteLine("Logout failed!");
            }

            _client = new ImapClient();

            //Create POP3 client with parameters needed
            //URL of host to connect to
            _client.Host = account.Host;
            //TCP port for connection
            _client.Port = (ushort)account.Port;
            //Username to login to the POP3 server
            _client.Username = account.Username;
            //Password to login to the POP3 server
            _client.Password = account.Password;

            _client.SSLInteractionType = Email.Net.Common.Configurations.EInteractionType.SSLPort;

            try
            {
                //Login to the server
                CompletionResponse response = _client.Login();
                if (response.CompletionResult != ECompletionResponseType.OK)
                {
                    MessageBox.Show("Error", String.Format("Connection error:\n {0}", response.Message), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    //Get all messages to know the uid
                    Mailbox folders = _client.GetMailboxTree();

                    iTalk.iTalk_TabControl tab = tabs[iTalk_TabControl.SelectedIndex];
                    tab.TabPages.Clear();

                    for (int i = 0; i <= folders.Children.Count - 1; i++)
                    {
                        tab.TabPages.Add(folders.Children[i].DisplayName + " - " + _client.GetMessageCount(folders.Children[i]));
                    }

                    GetMessages();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }

            this.Cursor = Cursors.Default;
        }