private void ConnectAndLogin(object param)
        {
            try
            {
                using (new BusyIndicator())
                {
                    string login    = Login.Trim();
                    string password = Password.Trim();
                    string imap     = Imap.Trim();
                    string smtp     = Smtp.Trim();

                    if (login == string.Empty || password == string.Empty || imap == string.Empty || smtp == string.Empty)
                    {
                        return;
                    }

                    _mailbox.ConnectToImapServer(imap, 993, true);
                    _mailbox.ConnectToSmtpServer(smtp, 465, true);

                    if (_mailbox.ImapLogin(login, password) && _mailbox.SmtpLogin(login, password))
                    {
                        Navigator.NavigateTo(new MailViewModel());
                    }
                    else
                    {
                        Error = "Неверный логин или пароль!";
                    }
                }
            }
            catch (Exception ex)
            {
                Error = "Во время соединения произошла ошибка. Проверьте правильность введенных данных!";
            }
        }
Ejemplo n.º 2
0
        private static void MailDLLExample()
        {
            using (Imap imap = new Imap())
            {
                //http://www.limilabs.com/mail/samples

                Console.WriteLine("Hello World");
                imap.Connect("imap.gmail.com",993,true);   // or ConnectSSL for SSL
                Console.WriteLine("SSL Connection Made");
                imap.UseBestLogin("USERNAME", "PASSWORD");
                Console.WriteLine("Login successful");

                imap.SelectInbox();
                List<long> uids = imap.Search(Flag.All);

                Console.WriteLine("Retrieved array of email id's");

                foreach (long uid in uids)
                {
                    IMail email = new MailBuilder()
                        .CreateFromEml(imap.GetMessageByUID(uid));

                    Console.WriteLine(email.Subject);

                    // save all attachments to disk
                    foreach (MimeData mime in email.Attachments)
                    {
                        mime.Save(mime.SafeFileName);
                    }
                }
                imap.Close();
            }
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            /* Connect to gmail using ssl. */
            Imap imap = new Imap("imap.gmail.com", 993, true);

            /* Authenticate using google email and password */
            //imap.Authenicate("uabandern", "passwordisreal");
            imap.Authenicate("6969test", "czerwonykaktus");

            /* Get a list of folders */
            var folders = imap.GetFolders();

            /* Select a mailbox */
            imap.SelectFolder("INBOX");

            /* Get message using UID */
            /* Second parameter is section type. e.g Plain text or HTML */
            //Console.WriteLine(imap.GetMessage("UID message number", "1"));

            /* Get message using index */
            //Console.WriteLine(imap.GetMessage(1, "1"));
            Console.WriteLine(imap.GetMessage(2, ""));

            /* Get total message count */
            Console.WriteLine("Messages:");
            Console.WriteLine(imap.GetMessageCount());

            /* Get total unseen message count */
            Console.WriteLine("Unseen messages:");
            Console.WriteLine(imap.GetUnseenMessageCount());

            Console.ReadKey();
        }
Ejemplo n.º 4
0
 public void MoveByUid(long uid, string destFolder)
 {
     using (Imap mailClient = CreateMailClient())
     {
         mailClient.MoveByUID(uid, GetOrCreateFolder(mailClient, destFolder));
     }
 }
        public Email GetMessageById(IMailboxSettings mailboxSettings, long emailId)
        {
            Email result = null;

            using (var imap = new Imap())
            {
                try
                {
                    var loggedIn = LoginToInbox(mailboxSettings, imap);

                    if (!loggedIn)
                        return null;

                    var eml = imap.PeekMessageByUID(emailId);
                    var email = new MailBuilder().CreateFromEml(eml);

                    result = EmailMapper.MapEmailToCoreEmail(mailboxSettings.AccountName, emailId, email);
                }
                catch (Exception ex)
                {
                    ApplyLabelToMessage(mailboxSettings, emailId, _mailboxLabels.InboundMailBoxErrorLabel);
                    MarkMessageAsRead(mailboxSettings, emailId);
                }
            }

            return result;
        }
Ejemplo n.º 6
0
        private Imap CreateMailClient()
        {
            var client = new Imap {
                ReceiveTimeout = new TimeSpan(0, 0, 10, 0), SendTimeout = new TimeSpan(0, 0, 10, 0)
            };

            if (Pars.UseSsl)
            {
                client.SSLConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
                openConnection(client.ConnectSSL, client.ConnectSSL, Pars);
            }
            else
            {
                openConnection(client.Connect, client.Connect, Pars);
            }

            client.UseBestLogin(Pars.Username, Pars.Password);
            client.ServerCertificateValidate += OnCertificateValidate;

            if (!string.IsNullOrEmpty(Pars.ImapFolder))
            {
                client.Select(Pars.ImapFolder);
            }
            else
            {
                client.SelectInbox();
            }

            return(client);
        }
Ejemplo n.º 7
0
        public void get_data_message()
        {
            try
            {
                string resultado;
                // C#
                using (Imap imap = new Imap())
                {
                    //puerto 110

                    imap.Connect("imap.gmail.com", 993, true);   // conneccion a host con el puerto
                    imap.UseBestLogin("*****@*****.**", "Facturacion2016");
                    imap.SelectInbox();

                    List <long> uids = imap.Search(Flag.Unseen);

                    foreach (long uid in uids)
                    {
                        IMail email = new MailBuilder().CreateFromEml(imap.GetMessageByUID(uid));

                        Console.WriteLine(email.Subject);
                        // guardar elementos en el disco
                        foreach (MimeData mime in email.Attachments)
                        {
                            mime.Save("c:/tyscom xml/respuestas_sii/" + mime.SafeFileName);
                        }
                    }
                    imap.Close();
                }
            }
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 8
0
        public Form1(string login, string password)
        {
            InitializeComponent();
            myDictionary.Add("All", Flag.All);
            myDictionary.Add("Unseen", Flag.Unseen);
            myDictionary.Add("Answered", Flag.Answered);



            using (Imap imap = new Imap())
            {
                imap.Connect("imap.mail.ru"); // or ConnectSSL for SSL
                imap.UseBestLogin(login, password);
                imap.SelectInbox();
                List <long> uids = imap.Search(Flag.All);
                int         step = 0;
                foreach (long uid in uids)
                {
                    if (step != 10)
                    {
                        var   eml   = imap.GetMessageByUID(uid);
                        IMail email = new MailBuilder()
                                      .CreateFromEml(eml);
                        listBox1.Items.Add(email.Subject + " " + email.Text);
                        step++;
                    }
                    else
                    {
                        continue;
                    }
                }
                imap.Close();
            }
        }
Ejemplo n.º 9
0
        private void buttonDelete_Click(object sender, EventArgs e)
        {
            if (comboBoxFolder.SelectedItem != null)
            {
                var folder = (String)comboBoxFolder.SelectedItem;

                if (MessageBox.Show(this, String.Format("Are you sure you want to delete {0} and all contents?", folder), "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    var mailbox = Mailbox;

                    using (var imap = new Imap(mailbox.HostName, mailbox.Port, mailbox.UserName, mailbox.Password, mailbox.ImapFolder))
                    {
                        imap.DeleteFolder(folder);

                        var cbMoveSelected = comboBoxMove.Text;

                        clearMessages = false;

                        comboBoxFolder.Items.Clear();
                        comboBoxMove.Items.Clear();
                        comboBoxMove.Text = String.Empty;

                        var folders = imap.GetFolderNames();
                        comboBoxFolder.Items.AddRange(folders);
                        comboBoxMove.Items.AddRange(folders);

                        comboBoxMove.SelectedIndex = comboBoxMove.FindString(cbMoveSelected);
                    }
                }
            }
        }
Ejemplo n.º 10
0
        static void Main()
        {
            using (Imap imap = new Imap())
            {
                imap.Connect(_server);                              // Use overloads or ConnectSSL if you need to specify different port or SSL.
                imap.Login(_user, _password);                       // You can also use: LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods,
                                                                    // or use UseBestLogin method if you want Mail.dll to choose for you.

                List <FolderInfo> folders = imap.GetFolders();      // List all folders on the IMAP server

                Console.WriteLine("Folders on IMAP server: ");
                foreach (FolderInfo folder in folders)
                {
                    FolderStatus status = imap.Examine(folder.Name);    // Examine each folder for number of total and recent messages

                    Console.WriteLine(                                  // Display folder information
                        string.Format("{0}, Recent: {1}, Total: {2}",
                                      folder.Name,
                                      status.MessageCount,
                                      status.Recent));
                }

                // You can also Create, Rename and Delete folders:
                imap.CreateFolder("Temporary");
                imap.RenameFolder("Temporary", "Temp");
                imap.DeleteFolder("Temp");

                imap.Close();
            }
        }
Ejemplo n.º 11
0
 private void ImapFolderDialog_Shown(object sender, EventArgs e)
 {
     using (var imap = new Imap(HostName, Port, UserName, Password))
     {
         AddFolders(imap, null, imap.ListFolders());
     }
 }
Ejemplo n.º 12
0
        public void GetAllMails(IProgress <IMail> progress, [Optional] FolderInfo folder)
        {
            using (Imap imap = new Imap())
            {
                imap.ConnectSSL(mailServer);
                imap.UseBestLogin(userData.UserMail, userData.Password);

                if (folder == null)
                {
                    imap.SelectInbox();
                }
                else
                {
                    imap.Select(folder);
                }

                List <long> uids = imap.Search(Flag.Unseen);
                NoofMails = uids.Count;
                foreach (long uid in uids)
                {
                    var   eml  = imap.GetMessageByUID(uid);
                    IMail mail = new MailBuilder().CreateFromEml(eml);

                    progress.Report(mail);
                }
                imap.Close();
            }
        }
Ejemplo n.º 13
0
        private void listViewMessages_DoubleClick(object sender, EventArgs e)
        {
            var mailbox = Mailbox;

            if (String.Compare((String)comboBoxFolder.SelectedItem, imapRoot, true) == 0 && IsServiceRunning() && mailbox.Enabled)
            {
                MessageBox.Show(this, "Cannot view messages from the root folder whilst Email Import service is running.", "Search", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (listViewMessages.SelectedItems.Count > 0)
            {
                try
                {
                    var item = listViewMessages.SelectedItems[0];
                    var uid  = Convert.ToInt64(item.SubItems[7].Text);

                    using (var imap = new Imap(mailbox.HostName, mailbox.Port, mailbox.UserName, mailbox.Password, (String)comboBoxFolder.SelectedItem))
                    {
                        var message = imap.DownloadMessage(uid);

                        var tmp = Path.Combine(Path.GetTempPath(), "tmp.eml");
                        message.SaveMessage(tmp);

                        Process.Start(tmp);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.ToString(), "View", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Ejemplo n.º 14
0
        static void Main()
        {
            using (Imap imap = new Imap())
            {
                imap.ConnectSSL(_server);                        // Use overloads or ConnectSSL if you need to specify different port or SSL.
                imap.Login(_user, _password);                    // You can also use: LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods,
                                                                 // or use UseBestLogin method if you want Mail.dll to choose for you.

                imap.SelectInbox();                              // You can select other folders, e.g. Sent folder: imap.Select("Sent");

                List <long> uids = imap.Search(Flag.Unseen);     // Find all unseen messages.

                Console.WriteLine("Number of unseen messages is: " + uids.Count);
                System.Speech.Synthesis.SpeechSynthesizer synth = new System.Speech.Synthesis.SpeechSynthesizer();

                synth.SetOutputToDefaultAudioDevice();
                String speak = "you have" + uids.Count.ToString();
                // Speak a string.
                synth.Speak(speak);

                foreach (long uid in uids)
                {
                    IMail email = new MailBuilder().CreateFromEml(  // Download and parse each message.
                        imap.GetMessageByUID(uid));

                    ProcessMessage(email);                          // Display email data, save attachments.
                }
                imap.Close();
            }
        }
        private Imap CreateImapClient(MailCredentials credentials)
        {
            Imap client = new Imap();

            SetImapLogging(client, credentials.SenderEmailAddress);
            if (credentials.StartTls)
            {
                client.SslMode = SslStartupMode.UseStartTlsIfSupported;
            }
            client.SslProtocol = SecurityProtocol.Auto;
            client.Timeout     = credentials.Timeout > 0 ? credentials.Timeout : _defaultCredentialsTimeout;
            try {
                if (credentials.Port > 0)
                {
                    client.Connect(credentials.Host, credentials.Port);
                }
                else
                {
                    client.Connect(credentials.Host);
                }
            } catch (Exception ex) {
                throw new ImapException(LocCanNotConnect.ToString(), ex);
            }
            if (credentials.UseSsl && !client.IsSslConnection)
            {
                throw new ImapException(LocServerNotSupportSslConnection);
            }
            return(client);
        }
Ejemplo n.º 16
0
        private void comboBoxMailbox_SelectedIndexChanged(object sender, EventArgs e)
        {
            var mailbox = Mailbox;

            try
            {
                comboBoxFolder.Items.Clear();
                comboBoxMove.Items.Clear();

                using (var imap = new Imap(mailbox.HostName, mailbox.Port, mailbox.UserName, mailbox.Password, mailbox.ImapFolder))
                {
                    imapRoot      = imap.RootFolder;
                    imapDelimiter = imap.Delimiter;

                    var folders = imap.GetFolderNames();
                    comboBoxFolder.Items.AddRange(folders);
                    comboBoxMove.Items.AddRange(folders);
                }

                comboBoxFolder.Enabled = true;
                comboBoxMove.Text      = null;
                buttonDelete.Enabled   = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 17
0
        private int DownloadEmail()
        {
            int count = 0;

            // Order the mailboxes by defined priority (or default of 5)
            var profiles = from profile in Settings.MailboxProfiles.Values
                           orderby profile.Priority
                           select profile;

            // Loop through each mailbox defined in the configuration file
            foreach (var profile in profiles)
            {
                // If the timer has been stopped, ImapCollector has been asked to stop, so stop the processing loop
                if (!timer.Enabled)
                {
                    break;
                }

                // Ignore if no imap host is defined
                if (String.IsNullOrWhiteSpace(profile.ImapHost))
                {
                    continue;
                }

                ConfigLogger.Instance.LogDebug("ImapCollector", String.Format("Processing mailbox {0}...", profile.Description));

                // Get the storage path (base path)
                var storagePath = String.IsNullOrWhiteSpace(profile.StoragePath) ? Settings.DefaultStoragePath : profile.StoragePath;

                // Log a warning and continue onto the next profile if no storage path available
                if (String.IsNullOrWhiteSpace(storagePath))
                {
                    ConfigLogger.Instance.LogWarning("ImapCollector", "Storage Path configuration not found.");
                    continue;
                }

                try
                {
                    // Create an imap session (auto connect/login/select)
                    using (Imap imap = new Imap(profile))
                    {
                        // Download the actual mail message
                        count += DownloadEmail(imap, profile, storagePath);

                        // Expunge any deleted messages
                        imap.ExpungeMessages();
                    }
                }
                catch (OutOfMemoryException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    ConfigLogger.Instance.LogError("ImapCollector", e);
                }
            }

            return(count);
        }
        /// <summary>
        /// Creates <see cref="ImapClient"/> instance.
        /// </summary>
        /// <param name="credentials"><see cref="MailCredentials"/> instance.</param>
        /// <param name="errorMessages"><see cref="ImapErrorMessages"/> instance.</param>
        /// <param name="userConnection"><see cref="UserConnection"/> instance.</param>
        /// <param name="login">Flag indicates if need to login to imap server.</param>
        public ImapClient(MailCredentials credentials, ImapErrorMessages errorMessages, UserConnection userConnection, bool login = true)
        {
            _userConnection     = userConnection;
            _client             = CreateImapClient(credentials);
            _remoteChangesCount = 0;
            LocalChangesCount   = 0;
            string errorMessage = string.Empty;

            try {
                _currentMailboxName = credentials.SenderEmailAddress;
                if (login)
                {
                    string oauthClassName = GetOAuthClientClassNameBySender(_currentMailboxName);
                    if (oauthClassName.IsNotNullOrEmpty())
                    {
                        errorMessage = LocInvalidOAuthCredentials.ToString();
#if !NETSTANDARD2_0 // TODO #CRM-42481
                        OAuthClient oauthClient = (OAuthClient)Activator.CreateInstance(Type.GetType("Terrasoft.Configuration." + oauthClassName), credentials.SenderEmailAddress, userConnection);
                        string      token       = oauthClient.GetAccessToken();
#else
                        string token = string.Empty;
#endif
                        string xoAuthKey = OAuth2.GetXOAuthKeyStatic(credentials.SenderEmailAddress, token);
                        _client.Login(credentials.UserName, xoAuthKey, AuthenticationMethods.SaslOAuth2, MailBee.AuthenticationOptions.None, null);
                    }
                    else
                    {
                        errorMessage = LocLoginOrPwdWrong.ToString();
                        _client.Login(credentials.UserName, credentials.UserPassword);
                    }
                }
            } catch (Exception ex) {
                throw new ImapException(errorMessage, ex);
            }
        }
Ejemplo n.º 19
0
        public static void TestReceiveEmail()
        {
            try
            {
                Imap imp = new Imap();
                imp.Connect("imap.126.com");
                imp.Login("*****@*****.**", "Aa00000000");
                imp.SelectFolder("Inbox");
                MailMessageCollection msgs = imp.DownloadMessageHeaders(Imap.AllMessages, false);
                // POP3 version: msgs = pop.DownloadMessageHeaders();
                imp.Disconnect();

                foreach (MailMessage msg in msgs)
                {
                    Console.WriteLine("From: " + msg.From.ToString());
                    Console.WriteLine("To: " + msg.To.ToString());
                    Console.WriteLine("Subject: " + msg.Subject);
                    Console.WriteLine();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Create Imap Connection
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        private static Imap CreateImapConnection(UserInformation userInfo)
        {
            // connect
            Imap imapC = new Imap();

            imapC.SendTimeout    = new TimeSpan(10, 0, 0);
            imapC.ReceiveTimeout = new TimeSpan(10, 0, 0);


            if (userInfo != null)
            {
                if (userInfo.UseSSL)
                {
                    imapC.SSLConfiguration.EnabledSslProtocols = SslProtocols.Ssl3;
                    // Ignore certificate errors
                    imapC.ServerCertificateValidate += (sender, e) => { e.IsValid = true; };

                    imapC.ConnectSSL(userInfo.Host, userInfo.HostPort);
                }
                else
                {
                    imapC.Connect(userInfo.Host, userInfo.HostPort);
                }

                // Login
                imapC.Login(userInfo.Username, userInfo.Password);
            }
            return(imapC);
        }
Ejemplo n.º 21
0
        private void btnProcessSelected_Click(object sender, RoutedEventArgs e)
        {
            foreach (var _removeMail in grdViewRemoveEmails.SelectedItems.ToList())
            {
                if (((RemoveMail)_removeMail).Subject.ToUpper() == "REMOVE")
                {
                    string[]       _body = ((RemoveMail)_removeMail).Body.Trim().Split(',');
                    string[]       _name = _body[0].Split(' ');
                    BankruptcyCase _case = BankruptcyCaseService.GetByNameAndZip(_name[0], "", _name[1], Int32.Parse(_body[1].Trim()));

                    if (_case != null)
                    {
                        _case.DontSend = true;
                        BankruptcyCaseService.Save(_case, false);

                        ((RemoveMail)_removeMail).Processed       = true;
                        ((RemoveMail)_removeMail).FoundAndRemoved = true;
                    }
                    else
                    {
                        ((RemoveMail)_removeMail).Processed       = true;
                        ((RemoveMail)_removeMail).FoundAndRemoved = false;
                    }

                    Imap.QuickDownloadMessages(ConfigurationManager.AppSettings["RemovePOP3Server"], ConfigurationManager.AppSettings["RemovePOP3User"], ConfigurationManager.AppSettings["RemovePOP3Password"], "Inbox");
                }
            }
        }
Ejemplo n.º 22
0
        private async Task <bool> ReadImapEmailBody(Imap imap, Email email)
        {
            return(await Task.Run(() =>
            {
                lock (email)
                {
                    if (string.IsNullOrEmpty(email.Body) && imap != null)
                    {
                        BodyStructure structure = imap.GetBodyStructureByUID(Convert.ToInt64(email.Uid));

                        if (structure?.Text != null)
                        {
                            email.Body = imap.GetTextByUID(structure.Text);
                            if (structure.Attachments.Count > 0)
                            {
                                // download attachment from email
                                saveAttachmentToDisk(email.Uid, imap);
                            }
                            return true;
                        }
                    }

                    return false;
                }
            }));
        }
Ejemplo n.º 23
0
        // create five different connection to server
        public async Task ServerConnections(Model.UserInfo userInfo)
        {
            // List To store server connections
            serverConnection = new List <Imap>();
            // atleast one connection required for Headers
            Imap imap = await ConnectImap(userInfo);

            serverConnection.Add(imap);
            // Run the others connections
            await Task.Run(async() =>
            {
                int numOfConnection = 5;
                int connFailure     = 0;

                for (int i = 0; i < numOfConnection - 1; i++)
                {
                    try
                    {
                        Imap imapconnections = await ConnectImap(userInfo);
                        serverConnection.Add(imapconnections);
                    }
                    catch (Exception)
                    {
                        connFailure++;
                        break;
                    }
                }
            });
        }
Ejemplo n.º 24
0
 private void updateMails(Flag selected)
 {
     using (Imap imap = new Imap())
     {
         listBox1.Items.Clear();
         imap.Connect("imap.mail.ru");   // or ConnectSSL for SSL
         imap.UseBestLogin(login, password);
         imap.SelectInbox();
         List <long> uids = imap.Search(selected);
         int         step = 0;
         foreach (long uid in uids)
         {
             if (step != 10)
             {
                 var   eml   = imap.GetMessageByUID(uid);
                 IMail email = new MailBuilder()
                               .CreateFromEml(eml);
                 listBox1.Items.Add(email.Subject + " " + email.Text);
                 step++;
             }
             else
             {
                 continue;
             }
         }
         imap.Close();
     }
 }
Ejemplo n.º 25
0
        private IEnumerable <IMailFolder> GetImapFolders()
        {
            Log.Debug("GetImapFolders()");

            var personal = Imap.GetFolders(Imap.PersonalNamespaces[0], true, CancelToken).ToList();

            if (!personal.Any(mb => mb.Name.Equals("inbox", StringComparison.InvariantCultureIgnoreCase)))
            {
                personal.Add(Imap.Inbox);
            }

            var folders = new List <IMailFolder>(personal);

            foreach (var folder in personal)
            {
                folders.AddRange(GetImapSubFolders(folder));
            }

            folders = folders.Distinct().ToList();

            if (folders.Count <= 1)
            {
                return(folders);
            }

            folders.Sort((f1, f2) => CompareFolders(f1, f2) ? -1 : CompareFolders(f2, f1) ? 1 : 0);

            return(folders);
        }
Ejemplo n.º 26
0
        public void Dispose()
        {
            Log.Info("MailClient->Dispose()");

            try
            {
                if (Imap != null)
                {
                    lock (Imap.SyncRoot)
                    {
                        if (Imap.IsConnected)
                        {
                            Log.Debug("Imap->Disconnect()");
                            Imap.Disconnect(true, CancelToken);
                        }

                        Imap.Dispose();
                    }
                }

                if (Pop != null)
                {
                    lock (Pop.SyncRoot)
                    {
                        if (Pop.IsConnected)
                        {
                            Log.Debug("Pop->Disconnect()");
                            Pop.Disconnect(true, CancelToken);
                        }

                        Pop.Dispose();
                    }
                }

                if (Smtp != null)
                {
                    lock (Smtp.SyncRoot)
                    {
                        if (Smtp.IsConnected)
                        {
                            Log.Debug("Smtp->Disconnect()");
                            Smtp.Disconnect(true, CancelToken);
                        }

                        Smtp.Dispose();
                    }
                }

                Authenticated = null;
                SendMessage   = null;
                GetMessage    = null;

                StopTokenSource.Dispose();
            }
            catch (Exception ex)
            {
                Log.Error("MailClient->Dispose(Mb_Id={0} Mb_Addres: '{1}') Exception: {2}", Account.MailBoxId,
                          Account.EMail.Address, ex.Message);
            }
        }
Ejemplo n.º 27
0
 public void MarkMessageSeen(long uid)
 {
     using (Imap mailClient = CreateMailClient())
     {
         mailClient.MarkMessageSeenByUID(uid);
     }
 }
        public void BaixarImap()
        {
            using (Imap imap = new Imap())
            {
                //imap.Connect("host sem SSL);
                imap.ConnectSSL(this.hostIMAP);
                imap.UseBestLogin(this.MeuEmaail, this.MinhaSenha);

                imap.SelectInbox();
                List <long> uids = imap.Search(Flag.All);

                foreach (long uid in uids)
                {
                    IMail email = new MailBuilder()
                                  .CreateFromEml(imap.GetMessageByUID(uid));

                    Console.WriteLine(email.Subject);

                    // salva anexo no disco
                    foreach (MimeData mime in email.Attachments)
                    {
                        mime.Save(string.Concat(this.PathAnexo, mime.SafeFileName));
                    }
                }
            }
        }
        static void Main(string[] args)
        {
            using (Imap imap = new Imap())
            {
                imap.ConnectSSL("imap.gmail.com");
                imap.UseBestLogin("*****@*****.**", "password for Gmail apps");
                // Recognize Trash folder
                List <FolderInfo> folders = imap.GetFolders();

                CommonFolders common = new CommonFolders(folders);

                FolderInfo trash = common.Trash;
                // Find all emails we want to delete
                imap.Select(trash);
                List <long> uidList = imap.Search(Flag.All);
                foreach (long uid in uidList)
                {
                    imap.DeleteMessageByUID(uid);
                    Console.WriteLine("{0} deleted", uid);
                }
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
                imap.Close();
            }
        }
Ejemplo n.º 30
0
        void ConnectToEmail()
        {
            using (Imap ourImap = new Imap())
            {
                TextBoxOfMessages.Text += "       Соединение установлено" + "\r\n";
                ourImap.Connect("imap.***.ru");
                ourImap.Login("YourMail", "MailPassword");
                ourImap.Select("Спам");

                spamMessagesList        = ourImap.Search(Flag.All);
                TextBoxOfMessages.Text += "Писем в папке \"Спам\" : " + spamMessagesList.Count + "\r\n";

                foreach (long id in spamMessagesList)
                {
                    IMail email = new MailBuilder().CreateFromEml(ourImap.GetMessageByUID(id));
                    CleanFromSymbols(email.Text); // убрал email.Subject т.к. кривые символы
                }

                ourImap.SelectInbox();
                inputMassageList        = ourImap.Search(Flag.Flagged);
                TextBoxOfMessages.Text += "Отмечено писем : " + inputMassageList.Count + "\r\n";

                ourImap.Close();
            }
        }
Ejemplo n.º 31
0
        private bool FetchMaessages(Imap imap)
        {
            UidCollection uids = (UidCollection)imap.Search(true, "UNSEEN", null);

            Log.Info("Unseen email count: {0}", uids.Count);

            bool handledMail = false;

            if (uids.Count > 0)
            {
                Log.Info("Fetching unseen messages...");

                MailMessageCollection msgs = imap.DownloadEntireMessages(uids.ToString(), true);

                foreach (MailMessage msg in msgs)
                {
                    Log.Info("Recent message index: {0} Subject: {1}", msg.IndexOnServer, msg.Subject);

                    if (msg.Subject.Contains(this.reqMailSubject))
                    {
                        Log.Info("Pacnet confirmation message has been received with subject: {0}", msg.Subject);
                        handledMail = true;
                        DB.ExecuteNonQuery(
                            "SetPacnetTopUpConfirmationRequestConfirmed",
                            CommandSpecies.StoredProcedure,
                            new QueryParameter("DateSent", this.dateSentReq),
                            new QueryParameter("DateConfirmed", TimeZoneInfo.ConvertTimeToUtc(msg.DateReceived))
                            );
                    }             // if has matching subject
                }                 // foreach email

                Log.Info("Fetching unseen messages complete.");
            }             // if
            return(handledMail);
        }
Ejemplo n.º 32
0
        static void Main(string[] args)
        {
            while (true)
            {
                using (Imap imap = new Imap())
                {
                    imap.ConnectSSL("imap.gmail.com"); // or ConnectSSL for SSL
                    imap.UseBestLogin(Email, PW);

                    imap.SelectInbox();
                    List <long> uidList = imap.Search(Flag.Unseen);
                    foreach (long uid in uidList)
                    {
                        IMail email = new MailBuilder()
                                      .CreateFromEml(imap.GetMessageByUID(uid));
                        string ExpressionToMatch = "hej";
                        if (Regex.IsMatch(email.Text, ExpressionToMatch))
                        {
                            SendEmail("i can see that your mail contained: " + ExpressionToMatch, email.ReturnPath);
                        }
                        Console.WriteLine(email.Text);
                        Console.WriteLine(email.ReturnPath);
                        Console.WriteLine(
                            "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////");
                    }

                    //Console.WriteLine("done press a key");
                    //Console.ReadKey();
                    //imap.Noop();
                    imap.Close();
                }
                Thread.Sleep(1000 * 10);
            }
        }
		public ImapMailBeeClient()
		{
			Imap.LicenseKey = MailBeeEmailClient.MAILBEE_LICENSE_KEY;

			// Make sure to disable throwing exception explicitly. Otherwise strange things might happen. See bug #5748 for details.
			// So please don't change this option unless you know what you are doing!!!
			_client = new Imap { ThrowExceptions = false };
		}
Ejemplo n.º 34
0
        static void Main(string[] args)
        {
            if ((args.Length < 2) || (args.Length > 3))
            {
                ShowInvalidArgumentsText();
            }
            else
            {
                try
                {
                    string username = args[0];
                    string password = args[1];
                    string imapServer = "imap.gmail.com";

                    if (args.Length == 3)
                    {
                        imapServer = args[2];
                    }

                    // Show menu
                    int optionChosen = ShowMenu();

                    using (Imap imap = new Imap())
                    {
                        // Connection to the Imap server
                        imap.ConnectSSL(imapServer);
                        // Login with username and password given
                        imap.Login(username, password);

                        // Program logic
                        switch (optionChosen)
                        {
                            case 1:
                                break;

                            case 2:
                                break;

                            case 0:
                                break;
                        }

                        // Closing connection to Imap server
                        imap.Close(true);
                    }
                }
                catch(ServerException ex)
                {
                    ShowInvalidArgumentsText();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: " + ex.GetType().ToString() + " occurred");
                    Console.WriteLine("Message: " + ex.Message);
                }
            }
        }
Ejemplo n.º 35
0
        public Imap Imap()
        {
            Imap imap = new Imap();

            try
            {
                imap.Connect(Server, 993, true);
                imap.Login(
                    Email.SecureStringToString(),
                    Password.SecureStringToString());
            }
            catch
            {
                imap = null;
            }

            return imap;
        }
Ejemplo n.º 36
0
        private static void GetUnseenEmails(Imap imap)
        {
            imap.SelectInbox();

            List<long> uids = imap.SearchFlag(Flag.Unseen);

            int counterMails = 1;
            int totalMails = uids.Count;

            foreach (long uid in uids)
            {
                string eml = imap.GetMessageByUID(uid);
                IMail email = new MailBuilder().CreateFromEml(eml);

                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine(email.Subject);
                Console.WriteLine(email.Text);

            }
        }
Ejemplo n.º 37
0
        public bool ApplyLabelToMessage(IMailboxSettings mailboxSettings, long emailId, string label)
        {
            var result = true;

            using (var imap = new Imap())
            {
                try
                {
                    var loggedIn = LoginToInbox(mailboxSettings, imap);

                    if (!loggedIn)
                        return false;

                    imap.GmailLabelMessageByUID(emailId, label);
                }
                catch (Exception ex)
                {
                    result = false;
                }
            }

            return result;
        }
Ejemplo n.º 38
0
        private void Form1_Load(object sender, EventArgs e)
        {
            imap = new Imap();
                imap.Connect("mail.telamon.com");
                imap.UseBestLogin("xinxin.he", "ICBC#*11180103hx");
                foreach (FolderInfo folder in imap.GetFolders())

                {

                    Console.WriteLine(folder.Name);

                }

                imap.Select("INBOX/2. Done/Greenfax");

                List<long> uids = imap.Search(Flag.All);

                foreach (long uid in uids)
                {

                    EmailList.Items.Add(uid);

                }
        }
Ejemplo n.º 39
0
        public List<long> GetEmails(IMailboxSettings mailboxSettings)
        {
            List<long> result;

            using (var imap = new Imap())
            {
                try
                {
                    var loggedIn = LoginToInbox(mailboxSettings, imap);

                    if (!loggedIn)
                        return null;

                    var searchCriteria = BuildSearchCriteria(mailboxSettings.Epoch);
                    result = imap.Search(Expression.And(searchCriteria));
                }
                catch (Exception ex)
                {
                    result = new List<long>();
                }
            }

            return result;
        }
Ejemplo n.º 40
0
        static void Main()
        {
            using (Imap imap = new Imap())
            {
                imap.Connect(_server);                              // Use overloads or ConnectSSL if you need to specify different port or SSL.
                imap.Login(_user, _password);                       // You can also use: LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods,
                                                                    // or use UseBestLogin method if you want Mail.dll to choose for you.

                imap.SelectInbox();                                 // You can select other folders, e.g. Sent folder: imap.Select("Sent");

                List<long> uids = imap.SearchFlag(Flag.Unseen);     // Find all unseen messages.
                
                Console.WriteLine("Number of unseen messages is: " + uids.Count);

                foreach (long uid in uids)
                {
                    IMail email = new MailBuilder().CreateFromEml(  // Download and parse each message.
                        imap.GetMessageByUID(uid));

                    ProcessMessage(email);                          // Display email data, save attachments.
                }
                imap.Close();
            }
        }
Ejemplo n.º 41
0
        static void Main(string[] args)
        {
            StreamWriter write = new StreamWriter(ConfigurationManager.AppSettings.Get("ErrorsPath"));

                using (Imap map = new Imap())
                {
                    map.ConnectSSL("imap.gmail.com");
                    map.Login("*****@*****.**", "algSweng500");

                    //select only the inbox to search and only show unread messages
                    map.SelectInbox();
                    List<long> uids = map.Search(Flag.Unseen);

                    foreach (long uid in uids)
                    {
                        try
                        {
                            string eml = map.GetMessageByUID(uid);
                            IMail mail = new MailBuilder().CreateFromEml(eml);

                            string title = mail.Subject;

                            if (!title.Contains("Please purchase"))
                            {

                                string message = mail.Text;

                                //get the stock symbol
                                string[] Symbolsplit = title.Split(new char[0]);
                                string symbol = Symbolsplit[1].ToString();

                                //get the amount to sell or buy
                                string AmountExtract = Regex.Match(title, @"\d+").Value;
                                int quantity = Int32.Parse(AmountExtract);

                                //convert the message and title to lowercase so the if statement will have no errors
                                message = message.ToLower();
                                title = title.ToLower();

                                PortfolioManager Manage = new PortfolioManager();
                                if (message.Contains("yes") && title.Contains("sell"))
                                {
                                    Manage.sell(symbol, quantity);
                                }
                                else if (message.Contains("yes") && title.Contains("buy"))
                                {
                                    Manage.buy(symbol, quantity);
                                }
                                else
                                {
                                    //adding just incase we find a need for it
                                }
                            }
                            else
                            {
                                map.MarkMessageUnseenByUID(uid);
                                write.WriteLine("Mail DLL ERROR");
                            }
                        }
                        catch (Exception ex)
                        {
                            write.WriteLine("Error Occurred Processing Email");
                            write.WriteLine("Email UID: " + uid);
                            write.WriteLine("Exception: " + ex.ToString());
                        }
                    }
                }
                write.Close();
        }
Ejemplo n.º 42
0
        public bool EmailVerification(string Email, string Password, ref GlobusHttpHelper globushttpHelper)
        {
            bool IsActivated = false;
            try
            {
                Log("[ " + DateTime.Now + " ] => [ Please Wait Account Verification Start... ]");

                System.Windows.Forms.Application.DoEvents();
                Chilkat.Http http = new Chilkat.Http();

                if (Email.Contains("@yahoo"))
                {
                    #region Yahoo Verification Steps

                    GlobusHttpHelper HttpHelper = new GlobusHttpHelper();
                    bool activate = false;
                    try
                    {
                        bool emaildata = false;
                        //Chilkat.Http http = new Chilkat.Http();
                        ///Chilkat Http Request to be used in Http Post...
                        Chilkat.HttpRequest req = new Chilkat.HttpRequest();
                        bool success;

                        // Any string unlocks the component for the 1st 30-days.
                        success = http.UnlockComponent("THEBACHttp_b3C9o9QvZQ06");
                        if (success != true)
                        {
                            Console.WriteLine(http.LastErrorText);
                            return false;
                        }

                        http.CookieDir = "memory";
                        http.SendCookies = true;
                        http.SaveCookies = true;

                        //http.ProxyDomain = "127.0.0.1";
                        //http.ProxyPort = 8888;
                        http.SetRequestHeader("Accept-Encoding", "gzip,deflate");
                        Chilkat.Imap iMap = new Imap();
                        string Username = Email;

                        iMap.UnlockComponent("THEBACIMAPMAILQ_OtWKOHoF1R0Q");
                        //iMap.
                        //iMap.HttpProxyHostname = "127.0.0.1";
                        //iMap.HttpProxyPort = 8888;

                        iMap.Port = 993;
                        iMap.Connect("imap.n.mail.yahoo.com");
                        iMap.Login(Email, Password);
                        iMap.SelectMailbox("Inbox");

                        // Get a message set containing all the message IDs
                        // in the selected mailbox.
                        Chilkat.MessageSet msgSet;
                        //msgSet = iMap.Search("FROM \"facebookmail.com\"", true);

                        msgSet = iMap.GetAllUids();

                        if (msgSet.Count <= 0)
                        {
                            msgSet = iMap.GetAllUids();
                        }

                        // Fetch all the mail into a bundle object.
                        Chilkat.Email email = new Chilkat.Email();
                        //bundle = iMap.FetchBundle(msgSet);
                        string strEmail = string.Empty;
                        List<string> lstData = new List<string>();
                        if (msgSet != null)
                        {
                            for (int i = 0; i < msgSet.Count; i++)
                            {
                                try
                                {
                                    email = iMap.FetchSingle(msgSet.GetId(i), true);
                                    strEmail = email.Subject;
                                    string emailHtml = email.GetHtmlBody();
                                    lstData.Add(strEmail);

                                    string from = email.From.ToString().ToLower();

                                    if (from.Contains("@linkedin.com"))
                                    {
                                        foreach (string href in GetUrlsFromString(email.Body))
                                        {
                                            try
                                            {

                                                if (href.Contains("http://www.linkedin.com/e/csrf") || href.Contains("http://www.linkedin.com/e/ato") || href.Contains("http://www.linkedin.com/e/v2?e"))
                                                {
                                                    string EscapeEmail = Uri.EscapeDataString(Email).Replace(".", "%2E").Trim();
                                                    {
                                                        string ConfirmationResponse = globushttpHelper.getHtmlfromUrl1(new Uri(href));
                                                        IsActivated = true;
                                                        break;
                                                    }

                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                Console.WriteLine("6 :" + ex.StackTrace);
                                            }
                                        }
                                    }
                                    if (IsActivated)
                                    {
                                        Log("[ " + DateTime.Now + " ] => [ Account : " + Email + " verified ]");
                                        break;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("Error >>> " + ex.StackTrace);
                                }
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("7 :" + ex.StackTrace);
                        Log("[ " + DateTime.Now + " ] => [ Email Verification Exception : " + ex.Message + "StackTrace --> >>>" + ex.StackTrace + " with : " + Email + " ]");
                        Log("[ " + DateTime.Now + " ] => [ Please check your Login Id and Password ]");
                    }
                    return IsActivated;
                    #endregion
                }
                else
                {
                    string Host = string.Empty;
                    int Port = 0;
                    if (Email.Contains("@gmail"))
                    {
                        Host = "pop.gmail.com";
                        Port = 995;
                    }
                    else if (Email.Contains("@hotmail"))
                    {
                        Host = "pop3.live.com";
                        Port = 995;
                    }
                    else if (Email.Contains("@gmx"))
                    {
                        Host = "pop.gmx.com";
                        Port = 995;
                    }
                    if (!string.IsNullOrEmpty(Host))
                    {
                        try
                        {
                            if (popClient.Connected)
                                popClient.Disconnect();
                            popClient.Connect(Host, Port, true);
                            popClient.Authenticate(Email, Password);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.StackTrace);

                            //retry once
                            System.Threading.Thread.Sleep(1000);

                            if (popClient.Connected)
                                popClient.Disconnect();
                            popClient.Connect(Host, Port, true);
                            popClient.Authenticate(Email, Password);
                        }

                        //if (!)
                        //{

                        //}

                        int Count = popClient.GetMessageCount();

                        for (int i = Count; i >= 1; i--)
                        {
                            try
                            {
                                OpenPOP.MIME.Message Message = popClient.GetMessage(i);
                                string subject = string.Empty;
                                subject = Message.Headers.Subject;
                                string frowwm = Message.Headers.From.ToString();
                                bool GoIntoEmail = false;

                                if (string.IsNullOrEmpty(subject))
                                {
                                    string from = Message.Headers.From.ToString().ToLower();
                                    if (from.Contains("linkedin.com"))
                                    {
                                        GoIntoEmail = true;
                                    }
                                }
                                try
                                {
                                    if (frowwm.Contains("linkedin.com"))
                                    //if(GoIntoEmail)
                                    {
                                        string Messagebody = Message.MessageBody[0];

                                        foreach (string href in GetUrlsFromStringGmail(Messagebody))
                                        {
                                            try
                                            {
                                                if (href.Contains("http://www.linkedin.com/e/csrf") || href.Contains("http://www.linkedin.com/e/ato") || href.Contains("http://www.linkedin.com/e/v2?e"))
                                                {
                                                  string  href1 = href.Replace("amp;",string.Empty);
                                                    string EscapeEmail = Uri.EscapeDataString(Email).Replace(".", "%2E").Trim();
                                                    {
                                                        string ConfirmationResponse = globushttpHelper.getHtmlfromUrl1(new Uri(href1));
                                                        IsActivated = true;
                                                        break;
                                                    }
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                Console.WriteLine("5 :" + ex.StackTrace);
                                            };
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("10 :" + ex.StackTrace);
                                    Log("[ " + DateTime.Now + " ] => [ Email Verification Exception : " + ex.Message + "StackTrace --> >>>" + ex.StackTrace + " with : " + Email + " ]");
                                }
                                if (IsActivated)
                                {

                                    break;
                                }
                            }
                            catch (Exception ex)
                            {
                                {
                                    Log("[ " + DateTime.Now + " ] => [ Email Verification Exception : " + ex.Message + "StackTrace --> >>>" + ex.StackTrace + " with : " + Email + " ]");
                                    Log("[ " + DateTime.Now + " ] => [ Please check your Login Id and Password ]");
                                }
                            }
                        }
                    }
                }
                return IsActivated;
            }
            catch (Exception ex)
            {
                Console.WriteLine("4 :" + ex.StackTrace);
                return IsActivated;
            }
        }
Ejemplo n.º 43
0
        // IMAP: GGet all messages in server (HostPOP) and after that, delete all od messages in that server
        public int GetMailIMAPDelete(string FolderName, string HostIMAP, int PortIMAP, bool SSLSupport, string MailName, string PWstring)
        {
            if (!imapConnect())
                return -1;

            //choose current folfer
            if (!imapClient.SelectMailbox(FolderName))
            {
                // if folder is not exist, create new folder
                imapClient.CreateMailbox(FolderName);
                imapClient.SelectMailbox(FolderName);
            }

            Imap subimapClient = new Imap();
            if (!subimapClient.UnlockComponent("IMAP-TEAMBEAN_17BDEB05021V"))
                return -1;
            //config info of imap server
            if (SSLSupport)      //if SSL support
                subimapClient.Ssl = true;
            else
                subimapClient.Ssl = false;
            subimapClient.Port = PortIMAP;
            //connect
            subimapClient.ConnectTimeout = 15;  // defaulf timeout = 30, so when it can't connect, it's too slow
            if (!subimapClient.Connect(HostIMAP))
                return -1;   // if can't connect to imap server

            if (!subimapClient.Login(MailName, PWstring))
                return -1;   // if can't login to imap server

            // choose folder Inbox on imap server
            // it's a little complex because the name of Inbox folder is diffirent on each imap server, such as INBOX, InBox, or InBox
            Mailboxes mailbox = subimapClient.ListMailboxes("", "*");
            for (int i = 0; i < mailbox.Count; i++)
            {
                if (mailbox.GetName(i).ToUpper() == "INBOX")
                {
                    if (!subimapClient.SelectMailbox(mailbox.GetName(i)))
                        return -1;
                    break;
                }
            }

            MessageSet OLdMSSet = imapClient.Search("ALL", true);   //info of all old messages in our server
            MessageSet MSSet = subimapClient.Search("ALL", true);   //info of all  messages in imap server
            if (MSSet.Count != 0)
            {
                // add new message
                for (int i = 0; i < MSSet.Count; i++)
                {
                    Email mail = subimapClient.FetchSingle(MSSet.GetId(i), true);
                    imapClient.AppendMail(FolderName, mail);
                }

                //delete message on server
                subimapClient.SetFlags(MSSet, "Deleted", 1);
                subimapClient.Expunge();

                // mark new message is unread
                imapClient.SelectMailbox(FolderName);
                MessageSet NewMSSet = imapClient.Search("ALL", true);
                for (int i = 0; i < OLdMSSet.Count; i++)
                    NewMSSet.RemoveId(OLdMSSet.GetId(i));
                imapClient.SetFlags(NewMSSet, "Seen", 0);
                //Email agwag = imapClient.FetchSingle(NewMSSet.GetId(0), true);
            }
            subimapClient.Disconnect();
            imapDisconnect();
            return MSSet.Count;
        }
Ejemplo n.º 44
0
        public bool TestConnectServer(ref string Error)
        {
            imapClient = new Imap();
            if (!imapClient.UnlockComponent("IMAP-TEAMBEAN_17BDEB05021V"))
                return false;

            if (SSL)      //if SSL support
                imapClient.Ssl = true;
            else
                imapClient.Ssl = false;

            imapClient.Port = Port;
            imapClient.ConnectTimeout = 10;
            //connect
            if (!imapClient.Connect(Host))
            {
                Error = "Server";
                return false;
            }

            if (!imapClient.Login(AccountLogin(UserName), Password))
            {
                AddMessageAccount();
                if (imapClient.Login(AccountLogin(UserName), Password))
                    return true;
                Error = "Account";
                return false;
            }
            return true;
        }
Ejemplo n.º 45
0
        //connect to Mail server throught IMAP
        public bool imapConnect()
        {
            imapClient = new Imap();
            if (!imapClient.UnlockComponent("IMAP-TEAMBEAN_17BDEB05021V"))
                return false;

            if (SSL)      //if SSL support
                imapClient.Ssl = true;
            else
                imapClient.Ssl = false;

            imapClient.Port = Port;
            //connect
            if (!imapClient.Connect(Host))
                return false;

            if (!imapClient.Login(AccountLogin(UserName), Password))
                return false;

            return true;
        }
Ejemplo n.º 46
0
 public MediaMail(Imap imap)
 {
     this.imap = imap;
     MediaTree = new MediaTree();
 }
Ejemplo n.º 47
0
        public bool GetYahooMails(string yahooEmail, string yahooPassword)
        {
            GlobusHttpHelper HttpHelper = new GlobusHttpHelper();
            bool activate = false;
            try
            {
                bool emaildata = false;

                Chilkat.Http http = new Chilkat.Http();

                ///Chilkat Http Request to be used in Http Post...
                Chilkat.HttpRequest req = new Chilkat.HttpRequest();
                bool success;

                // Any string unlocks the component for the 1st 30-days.
                success = http.UnlockComponent("THEBACHttp_b3C9o9QvZQ06");
                if (success != true)
                {
                    Console.WriteLine(http.LastErrorText);
                    return false;
                }
                http.CookieDir = "memory";
                http.SendCookies = true;
                http.SaveCookies = true;

                //http.ProxyDomain = "127.0.0.1";
                //http.ProxyPort = 8888;

                http.SetRequestHeader("Accept-Encoding", "gzip,deflate");

                Chilkat.Imap iMap = new Imap();
                string Username = yahooEmail;
                string Password = yahooPassword;
                //Username = "******";
                //Password = "******";
                iMap.UnlockComponent("THEBACIMAPMAILQ_OtWKOHoF1R0Q");

                //iMap.
                //iMap.HttpProxyHostname = "127.0.0.1";
                //iMap.HttpProxyPort = 8888;

                iMap.Connect("imap.n.mail.yahoo.com");
                iMap.Login(yahooEmail, yahooPassword);
                iMap.SelectMailbox("Inbox");

                // Get a message set containing all the message IDs
                // in the selected mailbox.
                Chilkat.MessageSet msgSet;
                //msgSet = iMap.Search("FROM \"facebookmail.com\"", true);
                msgSet = iMap.GetAllUids();

                // Fetch all the mail into a bundle object.
                Chilkat.Email email = new Chilkat.Email();
                //bundle = iMap.FetchBundle(msgSet);
                string strEmail = string.Empty;
                List<string> lstData = new List<string>();
                if (msgSet != null)
                {
                    for (int i = msgSet.Count; i > 0; i--)
                    {
                        email = iMap.FetchSingle(msgSet.GetId(i), true);
                        strEmail = email.Subject;
                        string emailHtml = email.GetHtmlBody();
                        lstData.Add(strEmail);

                        if (email.Subject.Contains("[WordPress] Activate") && email.Subject.Contains("wordpress.com"))
                        {
                            foreach (string href in GetUrlsFromString(email.Body))
                            {
                                try
                                {

                                    string staticUrl = string.Empty;

                                    staticUrl = href;
                                    responce = http.QuickGetStr(staticUrl);

                                    if (responce.Contains("Your account is now active"))
                                    {
                                        emaildata = true;
                                        //Log("your Account is activate now");
                                        activate = true;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex.StackTrace);
                                }
                            }
                        }
                    }
                }
                if (emaildata == false)
                {
                    Log("[ " + DateTime.Now + " ] => [ activation link is not find in user account so your Account is not activate please activate now ]");
                }
            }
            catch (Exception ex)
            {
            }
            return activate;
        }
Ejemplo n.º 48
0
        public bool MarkMessageAsRead(IMailboxSettings mailboxSettings, long emailId)
        {
            var result = true;

            using (var imap = new Imap())
            {
                try
                {
                    var loggedIn = LoginToInbox(mailboxSettings, imap);

                    if (!loggedIn)
                        return false;

                    imap.FlagMessageByUID(emailId, Flag.Seen);
                }
                catch (Exception ex)
                {
                    result = false;
                }

                imap.Close();
            }

            return result;
        }
Ejemplo n.º 49
0
        private bool LoginToInbox(IMailboxSettings mailboxSettings, Imap imap)
        {
            try
            {
                imap.ConnectSSL(mailboxSettings.InboundServerAddress, mailboxSettings.InboundServerPort);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            var accessToken = _oAuth2Authenticator.GetOAuth2AccessToken(mailboxSettings.MailboxAddress);

            if (string.IsNullOrEmpty(accessToken))
                return false;

            imap.LoginOAUTH2(mailboxSettings.MailboxAddress, accessToken);

            imap.SelectInbox();

            return true;
        }
Ejemplo n.º 50
0
 public void Setup() {
     var mailAccess = MailAccessRepository.LoadFrom("mailfollowup.imap.tests.mail.access.txt", Assembly.GetExecutingAssembly());
     sut = new Imap(mailAccess);
 }
Ejemplo n.º 51
0
        //connect to Mail server throught IMAP
        public static bool TestImapConnect(string host, int port, string username, string password, ref string Error)
        {
            Imap subimapClient = new Imap();
            if (!subimapClient.UnlockComponent("IMAP-TEAMBEAN_17BDEB05021V"))
                return false;

            if (SSL)      //if SSL support
                subimapClient.Ssl = true;
            else
                subimapClient.Ssl = false;

            subimapClient.Port = port;
            //connect
            if (!subimapClient.Connect(host))
            {
                Error = "Server";
                return false;
            }

            if (!subimapClient.Login(username, password))
            {
                Error = "Account";
                return false;
            }
            return true;
        }
        private bool LoginToInbox(IMailboxSettings mailboxSettings, Imap imap)
        {
            imap.ConnectSSL(mailboxSettings.ServerAddress, mailboxSettings.ServerPort);

            var accessToken = _oAuth2Authenticator.GetOAuth2AccessToken(mailboxSettings.MailboxAddress);

            if (string.IsNullOrEmpty(accessToken))
                return false;

            imap.LoginOAUTH2(mailboxSettings.MailboxAddress, accessToken);

            imap.SelectInbox();

            return true;
        }
Ejemplo n.º 53
0
    protected void btnSend_Click(object sender, EventArgs e)
    {
        SMS.APIType = SMSGateway.Site2SMS;
        SMS.MashapeKey = "pPsD7Kqfn2mshzjqhhbOkQMfGyQgp1TQAf7jsnRTMs6ygiLeUg";
        string text = "";
        //Email starts
        using (Imap imap = new Imap())
        {
            Limilabs.Mail.Log.Enabled = true;
            try
            {
                imap.ConnectSSL("imap.gmail.com", 993);   // or ConnectSSL for SSL

                imap.UseBestLogin("*****@*****.**", "zeesense40");
            }
            catch(Exception E)
            {
                return;
            }

            imap.SelectInbox();

            List<long> uids = imap.Search(Flag.All);



            foreach (long uid in uids)
            {

                var eml = imap.GetMessageByUID(uid);

                IMail email = new MailBuilder()

                    .CreateFromEml(eml);


                 text = email.Text;

                 
            
             
           }

            imap.Close();
        }
           
        //Email ends
            string[] arr=text.Split('~');
            string recvName = "",alert="";
        if(arr[0]=="&")
        {
            recvName = arr[2].ToLower().Trim();
            alert = arr[3];
        }
        else if(arr[0]=="^" || arr[0]=="%")
        {
            recvName = arr[2].ToLower().Trim();
            alert = arr[1];
        }
        //txtyourmoNumber.Text = "9742984490";
        SMS.Username = "******";
        //txtyourPassword.Text = "12345";
        SMS.Password = "******";
        //string recvName = arr[2].ToLower().Trim();
      //  string alert = arr[3];
        string phone = null;
        string tableName = "builder";
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);
                CloudTableClient tableClient1 = storageAccount.CreateCloudTableClient();
                CloudTable table1 = null;
                try
                {
                    table1 = tableClient1.GetTableReference(tableName);
                    TableQuery<CustomerEntity> query = new TableQuery<CustomerEntity>().Where(TableQuery.GenerateFilterCondition("customername", QueryComparisons.Equal, recvName.ToLower()));
                    List<CustomerEntity> AddressList = new List<CustomerEntity>();
                    CustomerEntity ce = new CustomerEntity();
                    foreach (CustomerEntity entity in table1.ExecuteQuery(query))
                    {
                        phone = entity.contactnumber;
                        break;
                    }
                    if (phone != null)
                    
                        SMS.SendSms(phone, alert);
                        //SendingRandomMessages(recvName, data).Wait();
                    
                }
               catch(Exception e1)
                {
                 
                }
    }
Ejemplo n.º 54
0
        public static void Initialize()
        {
            _continue = true;

            _log = LogManager.GetLogger(typeof(Program));
            XmlConfigurator.Configure();
            _log.Info("Logging initialized");

            //Set our thread priority to low
            Thread.CurrentThread.Priority = ThreadPriority.Lowest;
            _log.Info("Thread priority adjusted");

            SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);
            _log.Info("Exit handler initialized");

            Configuration configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            SmtpSection imap = configFile.GetSection("imap") as SmtpSection;
            _mailValues = imap.Network;
            _log.Info("e-mail settings inialized");

            EmailManager.Instance.HttpHost = ConfigurationManager.AppSettings["TargetHttpHost"].ToString();
            _log.Info("e-mail manager inialized");

            _emailClient = new Imap();

            _ctxManager = new ObjectContextManager();
            Provider.DbCtx = _ctxManager;
            _log.Info("InsideWord Database object context manager initialized");

            _idleTime = new TimeSpan(0, 20, 0);
            _log.Info("Initializing idle time to "+_idleTime.TotalMinutes+" minutes.");
        }
Ejemplo n.º 55
0
        private bool getAccessToken(string authCode)
        {
            bool getSuccess = false;
            string  accessToken="";
            if(RefreshKey_saved == "")
            {
            consumer.ClientCredentialApplicator =
                     ClientCredentialApplicator.PostParameter(clientSecret);

            IAuthorizationState grantedAccess1 = consumer.ProcessUserAuthorization(authCode);
            bool result=consumer.RefreshAuthorization(grantedAccess1, TimeSpan.FromHours(10));

            accessToken = grantedAccess1.AccessToken;

            // save key
            iniParser parser = new iniParser();
            String appStartPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
            parser.IniParser(iniPath);
            string _r=grantedAccess1.AccessToken;   //.RefreshToken;
            parser.AddSetting("Setup", "refreshkey", _r);
            parser.SaveSettings();
            myTabControl.SelectedIndex = 0;
            }
            else {
            // change code immediately
               //  consumer.RefreshAuthorization(grantedAccess1, TimeSpan.FromDays(30));
            //accessToken = grantedAccess1.AccessToken;
                 accessToken=RefreshKey_saved;
                 myTabControl.SelectedIndex = 0;
            }
                try
            {

                GoogleApi api = new GoogleApi(accessToken);

                // string user = "******"; // api.GetEmail();
                // GoogleApi api = new GoogleApi(accessToken);

                XmlDocument contacts = api.GetContacts();

                XmlNamespaceManager nsmgr = new XmlNamespaceManager(contacts.NameTable);
                nsmgr.AddNamespace("gd", "http://schemas.google.com/g/2005");
                nsmgr.AddNamespace("a", "http://www.w3.org/2005/Atom");
                emailCount = 0;
                foreach (XmlNode contact in contacts.GetElementsByTagName("entry"))
                {
                    XmlNode title = contact.SelectSingleNode("a:title", nsmgr);
                    XmlNode email = contact.SelectSingleNode("gd:email", nsmgr);

                    Console.WriteLine("{0}: {1}",
                        title.InnerText,
                        email.Attributes["address"].Value);
                    mail_arr.Add(email.Attributes["address"].Value);
                    emailCount++;
                 //   listbox1.Items.Add(title.InnerText + " , " + email.Attributes["address"].Value);
                }
                getSuccess = true;
            }
            catch (Exception err)
            {
               // MessageBox.Show("error: " + err.Message);
                Console.WriteLine("Error: " + err.Message);
                getSuccess = false;
                return getSuccess;
            }
            // everything is good, goto input : autocomplete
            contactData.inc(emailCount);
            int i = 0;
            foreach (string emailAddress in mail_arr)
            {
                contactData.States.SetValue(emailAddress, i);
                i++;
            }
            int where = contactData.States.Length;
            //
            AutoCompleteBox.ItemsSource = contactData.States;
            email_list.Items.Clear();
            label_invalid.Visibility = Visibility.Collapsed;
               // myTabControl.SelectedIndex = 0;
            return getSuccess;

            //------------------------
            try
            {
                // get inbox mail content
               // #region get InBox
                string user = "******"; // api.GetEmail();
                using (Imap imap = new Imap())
                {
                    imap.ConnectSSL("imap.gmail.com");
                    imap.LoginOAUTH2(user, accessToken);

                    imap.SelectInbox();
                    List<long> uids = imap.Search(Flag.Unseen);

                    foreach (long uid in uids)
                    {
                        string eml = imap.GetMessageByUID(uid);
                        IMail email = new MailBuilder().CreateFromEml(eml);

                       // listbox1.Items.Add(email.From);
                    }
                    imap.Close();
                }
            }
            catch (Exception err)
            {
                MessageBox.Show("error: " + err.Message);
            }
        }
Ejemplo n.º 56
0
       public override Email readEmail(string email, string password, string proxyAddress, string proxyPort, string proxyUser, string proxyPassword, string DOB, ref GlobusHttpHelper HttpHelper, string registrationstatus)
       {
           //throw new NotImplementedException();//Ajay to code this part

           Email objEmail = new Email();

           string yahooEmail = string.Empty;
           string yahooPassword = string.Empty;
           string Username = string.Empty;
           string Password = string.Empty;
           try
           {
               objEmail.username = email;
               objEmail.password = password;

               string realEmail = email;

               yahooEmail = email; ;
               yahooPassword = password;

               Chilkat.Imap iMap = new Imap();

               // Code For [email protected]
               if (yahooEmail.Contains("+") || yahooEmail.Contains("%2B"))
               {
                   try
                   {
                       string replacePart = yahooEmail.Substring(yahooEmail.IndexOf("+"), (yahooEmail.IndexOf("@", yahooEmail.IndexOf("+")) - yahooEmail.IndexOf("+"))).Replace("+", string.Empty);
                       yahooEmail = yahooEmail.Replace("+", string.Empty).Replace("%2B", string.Empty).Replace(replacePart, string.Empty);
                   }
                   catch (Exception ex)
                   {
                       GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
                   }
               }

               Username = yahooEmail;
               Password = yahooPassword;
               //Username = "******";
               //Password = "******";
               iMap.UnlockComponent("THEBACIMAPMAILQ_OtWKOHoF1R0Q");

               //iMap.
               //iMap.HttpProxyHostname = "127.0.0.1";
               //iMap.HttpProxyPort = 8888;

               iMap.Connect("imap.n.mail.yahoo.com");
               iMap.Login(yahooEmail, yahooPassword);
               iMap.SelectMailbox("Inbox");

               // Get a message set containing all the message IDs
               // in the selected mailbox.
               Chilkat.MessageSet msgSet;
               //msgSet = iMap.Search("FROM \"facebookmail.com\"", true);
               msgSet = iMap.GetAllUids();

               // Fetch all the mail into a bundle object.
               Chilkat.Email cEemail = new Chilkat.Email();
               //bundle = iMap.FetchBundle(msgSet);
               string strEmail = string.Empty;
               List<string> lstData = new List<string>();
               if (msgSet != null)
               {
                   for (int i = msgSet.Count; i > 0; i--)
                   {
                       cEemail = iMap.FetchSingle(msgSet.GetId(i), true);
                       strEmail = cEemail.Subject;
                       string emailHtml = cEemail.GetHtmlBody();
                       lstData.Add(strEmail);
                       if (cEemail.Subject.Contains("Action Required: Confirm Your Facebook Account"))
                       {
                           foreach (string href in GetUrlsFromString(cEemail.Body))
                           {
                               try
                               {
                                   string staticUrl = string.Empty;
                                   string email_open_log_picUrl = string.Empty;

                                   string strBody = cEemail.Body;
                                   string[] arr = Regex.Split(strBody, "src=");
                                   // string[] arr = Regex.Split(strBody, "href=");
                                   foreach (string item in arr)
                                   {
                                       if (!item.Contains("<!DOCTYPE"))
                                       {
                                           if (item.Contains("static"))
                                           {
                                               string[] arrStatic = item.Split('"');
                                               staticUrl = arrStatic[1];
                                           }
                                           if (item.Contains("email_open_log_pic"))
                                           {
                                               string[] arrlog_pic = item.Split('"');
                                               email_open_log_picUrl = arrlog_pic[1];
                                               email_open_log_picUrl = email_open_log_picUrl.Replace("amp;", "");
                                               break;
                                           }
                                       }
                                   }

                                   string href1 = href.Replace("&amp;report=1", "");
                                   href1 = href.Replace("amp;", "");

                                   objEmail.body = strBody;
                                   objEmail.subject = cEemail.Subject;
                                   objEmail.to = cEemail.ReplyTo;



                                   objEmail.from = cEemail.From.ToString();

                                   objEmail.mailType = MailType.yahoomail;

                                   EmailVerificationMultithreadedForAccountCreater(href1, staticUrl, email_open_log_picUrl, realEmail, yahooPassword, proxyAddress, proxyPort, proxyUser, proxyPassword);
                                   //LoginVerfy(href1, staticUrl, email_open_log_picUrl);
                                   break;
                               }
                               catch (Exception ex)
                               {
                                   Console.WriteLine(ex.StackTrace);
                               }
                           }
                           //return;
                       }
                       else if (cEemail.Subject.Contains("Just one more step to get started on Facebook"))
                       {
                           foreach (string href in GetUrlsFromString(cEemail.Body))
                           {
                               try
                               {
                                   string staticUrl = string.Empty;
                                   string email_open_log_picUrl = string.Empty;
                                   string verifyhref = string.Empty;
                                   string strBody = cEemail.Body;
                                   string[] arr = Regex.Split(strBody, "src=");
                                   string[] arr1 = Regex.Split(strBody, "href=");
                                   foreach (string item in arr)
                                   {
                                       if (!item.Contains("<!DOCTYPE"))
                                       {
                                           if (item.Contains("static"))
                                           {
                                               string[] arrStatic = item.Split('"');
                                               staticUrl = arrStatic[1];
                                           }
                                           if (item.Contains("email_open_log_pic"))
                                           {
                                               string[] arrlog_pic = item.Split('"');
                                               email_open_log_picUrl = arrlog_pic[1];
                                               email_open_log_picUrl = email_open_log_picUrl.Replace("amp;", "");
                                               break;
                                           }
                                       }
                                   }

                                   foreach (string item1 in arr1)
                                   {
                                       if (item1.Contains("confirmemail.php"))
                                       {
                                           string[] itemurl = Regex.Split(item1, "\"");
                                           verifyhref = itemurl[1].Replace("\"", string.Empty);
                                       }
                                   }

                                   string href1 = verifyhref.Replace("&amp;report=1", "");
                                   string href11 = href1.Replace("amp;", "");

                                   objEmail.body = strBody;
                                   objEmail.subject = cEemail.Subject;
                                   objEmail.to = cEemail.ReplyTo;



                                   objEmail.from = cEemail.From.ToString();

                                   objEmail.mailType = MailType.yahoomail;

                                   //string href1 = href.Replace("&amp;report=1", "");
                                   //href1 = href.Replace("amp;", "");
                                   if (href.Contains("confirmemail.php") && email_open_log_picUrl.Contains("email_open_log_pic.php"))
                                   {
                                       EmailVerificationMultithreadedForAccountCreater(href11, staticUrl, email_open_log_picUrl, realEmail, yahooPassword, proxyAddress, proxyPort, proxyUser, proxyPassword);
                                       //LoginVerfy(href1, staticUrl, email_open_log_picUrl);
                                       break;
                                   }
                               }
                               catch (Exception ex)
                               {
                                   GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
                               }
                           }
                           //return;
                       }

                       //*****************************************************bysanjeev**********************
                       else if (cEemail.Subject.Contains("Facebook Email Verification"))
                       {
                           foreach (string href in GetUrlsFromString(cEemail.Body))
                           {
                               try
                               {
                                   string staticUrl = string.Empty;
                                   string email_open_log_picUrl = string.Empty;
                                   string verifyhref = string.Empty;

                                   string strBody = cEemail.Body;
                                   string[] arr = Regex.Split(strBody, "src=");
                                   string[] arr1 = Regex.Split(strBody, "href=");
                                   // string[] arr = Regex.Split(strBody, "src=");
                                   foreach (string item in arr)
                                   {
                                       if (!item.Contains("<!DOCTYPE"))
                                       {
                                           if (item.Contains("static"))
                                           {
                                               string[] arrStatic = item.Split('"');
                                               staticUrl = arrStatic[1];
                                           }
                                           if (item.Contains("email_open_log_pic"))
                                           {
                                               string[] arrlog_pic = item.Split('"');
                                               email_open_log_picUrl = arrlog_pic[1];
                                               email_open_log_picUrl = email_open_log_picUrl.Replace("amp;", "");
                                               break;
                                           }
                                       }
                                   }
                                   foreach (string item1 in arr1)
                                   {
                                       if (item1.Contains("confirmcontact.php"))
                                       {
                                           string[] itemurl = Regex.Split(item1, "\"");
                                           verifyhref = itemurl[1].Replace("\"", string.Empty);
                                       }
                                   }


                                   //string href1 = href.Replace("&amp;report=1", "");
                                   //href1 = href.Replace("&amp", "");

                                   objEmail.body = strBody;
                                   objEmail.subject = cEemail.Subject;
                                   objEmail.to = cEemail.ReplyTo;



                                   objEmail.from = cEemail.From.ToString();

                                   objEmail.mailType = MailType.yahoomail;

                                   if (href.Contains("confirmcontact.php") && email_open_log_picUrl.Contains("email_open_log_pic.php"))
                                   {
                                       EmailVerificationMultithreadedForAccountCreater(verifyhref, staticUrl, email_open_log_picUrl, realEmail, yahooPassword, proxyAddress, proxyPort, proxyUser, proxyPassword);
                                       break;
                                   }//LoginVerfy(href1, staticUrl, email_open_log_picUrl);

                               }
                               catch (Exception ex)
                               {
                                   GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
                               }
                           }
                           //return;
                       }

                       //****************************************************************************************

                   }
               }
           }
           catch (Exception ex)
           {
               GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
           }

           return objEmail;
       }
Ejemplo n.º 57
0
 private string ParseBodyPart(Imap.BodyPartEncoding encoding)
 {
     return ParseBodyPart(encoding, null);
 }
Ejemplo n.º 58
0
 public void AddMailConnection(string newUser, Imap newConnection)
 {
     lock (_lock)
     {
         mailConnections.Add(newUser, newConnection);
     }
 }
Ejemplo n.º 59
0
 private string ParseBodyPart(Imap.BodyPartEncoding encoding, Encoding en)
 {
     string response;
     StringBuilder sb = new StringBuilder("");
     do
     {
         response = Connection.Read();
         if (Regex.IsMatch(response, patFetchComplete))
             break;
         if (encoding == Imap.BodyPartEncoding.BASE64)
             sb.Append(response);
         else if (encoding == Imap.BodyPartEncoding.QUOTEDPRINTABLE)
             if (response.EndsWith("=") || response.EndsWith(")"))
                 sb.Append(response.Substring(0, response.Length - 1));
             else
                 sb.AppendLine(response);
         else
             sb.AppendLine(response);
     } while (true);
     //} while (!(response.EndsWith("==") || response == ")"));
     if (sb.ToString().Trim().EndsWith(")"))
         sb = sb.Remove(sb.ToString().LastIndexOf(")"), 1);
     if (encoding != BodyPartEncoding.BASE64)
         return ImapDecode.Decode(sb.ToString(), en);
     return sb.ToString();
 }
Ejemplo n.º 60
-9
        static void Main()
        {
            using (Imap imap = new Imap())
            {
                imap.Connect(_server);              // Use overloads or ConnectSSL if you need to specify different port or SSL.
                imap.Login(_user, _password);       // You can also use: LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods,
                                                    // or use UseBestLogin method if you want Mail.dll to choose for you.
                imap.SelectInbox();
                                                    // All search methods return list of unique ids of found messages.

                List<long> unseen = imap.SearchFlag(Flag.Unseen);           // Simple 'by flag' search.

                List<long> unseenReports = imap.Search(new SimpleImapQuery  // Simple 'by query object' search.
                {
                    Subject = "report",
                    Unseen = true,
                });

                List<long> unseenReportsNotFromAccounting = imap.Search(    // Most advanced search using ExpressionAPI.
                    Expression.And(
                        Expression.Subject("Report"),
                        Expression.HasFlag(Flag.Unseen),
                        Expression.Not(
                            Expression.From("*****@*****.**"))
                ));

                foreach (long uid in unseenReportsNotFromAccounting)        // Download emails from the last result.
                {
                    IMail email = new MailBuilder().CreateFromEml(
                        imap.GetMessageByUID(uid));
                    Console.WriteLine(email.Subject);
                }

                imap.Close();
            }
        }