Пример #1
0
        static void Run()
        {
            // ExStart: ListingMessagesWithPagingSupport
            ///<summary>
            /// This example shows the paging support of ImapClient for listing messages from the server
            /// Available in Aspose.Email for .NET 6.4.0 and onwards
            ///</summary>
            using (ImapClient client = new ImapClient("host.domain.com", 993, "username", "password"))
            {
                try
                {
                    int         messagesNum  = 12;
                    int         itemsPerPage = 5;
                    MailMessage message      = null;
                    // Create some test messages and append these to server's inbox
                    for (int i = 0; i < messagesNum; i++)
                    {
                        message = new MailMessage(
                            "*****@*****.**",
                            "*****@*****.**",
                            "EMAILNET-35157 - " + Guid.NewGuid(),
                            "EMAILNET-35157 Move paging parameters to separate class");
                        client.AppendMessage(ImapFolderInfo.InBox, message);
                    }

                    // List messages from inbox
                    client.SelectFolder(ImapFolderInfo.InBox);
                    ImapMessageInfoCollection totalMessageInfoCol = client.ListMessages();
                    // Verify the number of messages added
                    Console.WriteLine(totalMessageInfoCol.Count);

                    ////////////////// RETREIVE THE MESSAGES USING PAGING SUPPORT////////////////////////////////////

                    List <ImapPageInfo> pages    = new List <ImapPageInfo>();
                    ImapPageInfo        pageInfo = client.ListMessagesByPage(itemsPerPage);
                    Console.WriteLine(pageInfo.TotalCount);
                    pages.Add(pageInfo);
                    while (!pageInfo.LastPage)
                    {
                        pageInfo = client.ListMessagesByPage(pageInfo.NextPage);
                        pages.Add(pageInfo);
                    }
                    int retrievedItems = 0;
                    foreach (ImapPageInfo folderCol in pages)
                    {
                        retrievedItems += folderCol.Items.Count;
                    }
                    Console.WriteLine(retrievedItems);
                }
                finally
                {
                }
            }
            // ExEnd: ListingMessagesWithPagingSupport
        }
        /// <summary>
        /// Recursive method to get messages from folders and sub-folders
        /// </summary>
        /// <param name="folderInfo"></param>
        /// <param name="rootFolder"></param>
        private static void ListMessagesInFolder(ImapFolderInfo folderInfo, string rootFolder, ImapClient client)
        {
            // Create the folder in disk (same name as on IMAP server)
            string currentFolder = Path.Combine(Path.GetFullPath("../../../Data/"), folderInfo.Name);

            Directory.CreateDirectory(currentFolder);

            // Read the messages from the current folder, if it is selectable
            if (folderInfo.Selectable == true)
            {
                // Send status command to get folder info
                ImapFolderInfo folderInfoStatus = client.ListFolder(folderInfo.Name);
                Console.WriteLine(folderInfoStatus.Name + " folder selected. New messages: " + folderInfoStatus.NewMessageCount +
                                  ", Total messages: " + folderInfoStatus.TotalMessageCount);

                // Select the current folder
                client.SelectFolder(folderInfo.Name);
                // List messages
                ImapMessageInfoCollection msgInfoColl = client.ListMessages();
                Console.WriteLine("Listing messages....");
                foreach (ImapMessageInfo msgInfo in msgInfoColl)
                {
                    // Get subject and other properties of the message
                    Console.WriteLine("Subject: " + msgInfo.Subject);
                    Console.WriteLine("Read: " + msgInfo.IsRead + ", Recent: " + msgInfo.Recent + ", Answered: " + msgInfo.Answered);

                    // Get rid of characters like ? and :, which should not be included in a file name
                    string fileName = msgInfo.Subject.Replace(":", " ").Replace("?", " ");

                    // Save the message in MSG format
                    MailMessage msg = client.FetchMessage(msgInfo.SequenceNumber);
                    msg.Save(currentFolder + "\\" + fileName + "-" + msgInfo.SequenceNumber + ".msg", Aspose.Email.Mail.SaveOptions.DefaultMsgUnicode);
                }
                Console.WriteLine("============================\n");
            }
            else
            {
                Console.WriteLine(folderInfo.Name + " is not selectable.");
            }

            try
            {
                // If this folder has sub-folders, call this method recursively to get messages
                ImapFolderInfoCollection folderInfoCollection = client.ListFolders(folderInfo.Name);
                foreach (ImapFolderInfo subfolderInfo in folderInfoCollection)
                {
                    ListMessagesInFolder(subfolderInfo, rootFolder, client);
                }
            }
            catch (Exception) { }
        }
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir  = RunExamples.GetDataDir_IMAP();
            string dstEmail = dataDir + "1234.eml";

            //Create an instance of the ImapClient class
            ImapClient client = new ImapClient();

            //Specify host, username and password for your client
            client.Host = "imap.gmail.com";

            // Set username
            client.Username = "******";

            // Set password
            client.Password = "******";

            // Set the port to 993. This is the SSL port of IMAP server
            client.Port = 993;

            // Enable SSL
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                // Select the inbox folder
                client.SelectFolder(ImapFolderInfo.InBox);

                // Get the message info collection
                ImapMessageInfoCollection list = client.ListMessages();

                // Download each message
                for (int i = 0; i < list.Count; i++)
                {
                    //Save the EML file locally
                    client.SaveMessage(list[i].UniqueId, dataDir + list[i].UniqueId + ".eml");
                }

                //Disconnect to the remote IMAP server
                client.Disconnect();
            }
            catch (Exception ex)
            {
                System.Console.Write(Environment.NewLine + ex.ToString());
            }

            Console.WriteLine(Environment.NewLine + "Downloaded messages from IMAP server.");
        }
Пример #4
0
        public static void Run()
        {
            // ExStart:ListingMessagesRecursively
            // Create an imapclient with host, user and password
            ImapClient client = new ImapClient();

            client.Host     = "domain.com";
            client.Username = "******";
            client.Password = "******";
            client.SelectFolder("InBox");
            ImapMessageInfoCollection msgsColl = client.ListMessages(true);

            Console.WriteLine("Total Messages: " + msgsColl.Count);
            // ExEnd:ListingMessagesRecursively
        }
        public static void Run()
        {
            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();

            // Specify host, username, password, port and SecurityOptions for your client
            client.Host            = "imap.gmail.com";
            client.Username        = "******";
            client.Password        = "******";
            client.Port            = 993;
            client.SecurityOptions = SecurityOptions.Auto;
            try
            {
                //ExStart:SetCustomFlag
                // Create a message
                MailMessage message = new MailMessage("*****@*****.**", "*****@*****.**", "subject", "message");

                //Append the message to mailbox
                string uid = client.AppendMessage(ImapFolderInfo.InBox, message);

                //Add custom flags to the added messge
                client.AddMessageFlags(uid, ImapMessageFlags.Keyword("custom1") | ImapMessageFlags.Keyword("custom1_0"));

                //Retreive the messages for checking the presence of custom flag
                client.SelectFolder(ImapFolderInfo.InBox);

                ImapMessageInfoCollection messageInfos = client.ListMessages();
                foreach (var inf in messageInfos)
                {
                    ImapMessageFlags[] flags = inf.Flags.Split();

                    if (inf.ContainsKeyword("custom1"))
                    {
                        Console.WriteLine("Keyword found");
                    }
                }

                //ExEnd:SetCustomFlag

                Console.WriteLine("Setting Custom Flag to Message example executed successfully!");
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
        }
Пример #6
0
        public static void Run()
        {
            try
            {
                // ExStart:RetrieveExtraParametersAsSummaryInformation
                using (ImapClient client = new ImapClient("host.domain.com", "username", "password"))
                {
                    MailMessage message = new MailMessage("*****@*****.**", "*****@*****.**", "EMAILNET-38466 - " + Guid.NewGuid().ToString(), "EMAILNET-38466 Add extra parameters for UID FETCH command");

                    // append the message to the server
                    string uid = client.AppendMessage(message);

                    // wait for the message to be appended
                    Thread.Sleep(5000);

                    // Define properties to be fetched from server along with the message
                    string[] messageExtraFields = new string[] { "X-GM-MSGID", "X-GM-THRID" };

                    // retreive the message summary information using it's UID
                    ImapMessageInfo messageInfoUID = client.ListMessage(uid, messageExtraFields);

                    // retreive the message summary information using it's sequence number
                    ImapMessageInfo messageInfoSeqNum = client.ListMessage(1, messageExtraFields);

                    // List messages in general from the server based on the defined properties
                    ImapMessageInfoCollection messageInfoCol = client.ListMessages(messageExtraFields);

                    ImapMessageInfo messageInfoFromList = messageInfoCol[0];

                    // verify that the parameters are fetched in the summary information
                    foreach (string paramName in messageExtraFields)
                    {
                        Console.WriteLine(messageInfoFromList.ExtraParameters.ContainsKey(paramName));
                        Console.WriteLine(messageInfoUID.ExtraParameters.ContainsKey(paramName));
                        Console.WriteLine(messageInfoSeqNum.ExtraParameters.ContainsKey(paramName));
                    }
                }
                // ExEnd:RetrieveExtraParametersAsSummaryInformation
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }
Пример #7
0
        public static void Run()
        {
            // Connect and log in to POP3
            const string host     = "host";
            const int    port     = 143;
            const string username = "******";
            const string password = "******";
            ImapClient   client   = new ImapClient(host, port, username, password);

            try
            {
                MailQueryBuilder builder = new MailQueryBuilder();

                // ExStart:CombineQueriesWithAND
                // Emails from specific host, get all emails that arrived before today and all emails that arrived since 7 days ago
                builder.From.Contains("SpecificHost.com");
                builder.InternalDate.Before(DateTime.Now);
                builder.InternalDate.Since(DateTime.Now.AddDays(-7));
                // ExEnd:CombineQueriesWithAND

                // Build the query and Get list of messages
                MailQuery query = builder.GetQuery();
                ImapMessageInfoCollection messages = client.ListMessages(query);
                Console.WriteLine("Imap: " + messages.Count + " message(s) found.");

                builder = new MailQueryBuilder();

                // ExStart:CombiningQueriesWithOR
                // Specify OR condition
                builder.Or(builder.Subject.Contains("test"), builder.From.Contains("*****@*****.**"));
                // ExEnd:CombiningQueriesWithOR

                // Build the query and Get list of messages
                query    = builder.GetQuery();
                messages = client.ListMessages(query);
                Console.WriteLine("Imap: " + messages.Count + " message(s) found.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
 public static void Run()
 {
     // ExStart:RetrievingMessagesAsynchronously
     // Connect and log in to IMAP
     using (ImapClient client = new ImapClient("host", "username", "password"))
     {
         client.SelectFolder("Issues/SubFolder");
         ImapMessageInfoCollection messages = client.ListMessages();
         AutoResetEvent            evnt     = new AutoResetEvent(false);
         MailMessage   message  = null;
         AsyncCallback callback = delegate(IAsyncResult ar)
         {
             message = client.EndFetchMessage(ar);
             evnt.Set();
         };
         client.BeginFetchMessage(messages[0].SequenceNumber, callback, null);
         evnt.WaitOne();
     }
     // ExEnd:RetrievingMessagesAsynchronously
 }
Пример #9
0
        // ExStart:ExchangeServerUsesSSL
        public static void Run()
        {
            // Connect to Exchange Server using ImapClient class
            ImapClient imapClient = new ImapClient("ex07sp1", 993, "Administrator", "Evaluation1", new RemoteCertificateValidationCallback(RemoteCertificateValidationHandler));

            imapClient.SecurityOptions = SecurityOptions.SSLExplicit;

            // Select the Inbox folder
            imapClient.SelectFolder(ImapFolderInfo.InBox);

            // Get the list of messages
            ImapMessageInfoCollection msgCollection = imapClient.ListMessages();

            foreach (ImapMessageInfo msgInfo in msgCollection)
            {
                Console.WriteLine(msgInfo.Subject);
            }
            // Disconnect from the server
            imapClient.Dispose();
        }
Пример #10
0
        public static void Run()
        {
            //ExStart:DeleteMultipleMessages
            using (ImapClient client = new ImapClient("exchange.aspose.com", "username", "password"))
            {
                try
                {
                    Console.WriteLine(client.UidPlusSupported.ToString());
                    // Append some test messages
                    client.SelectFolder(ImapFolderInfo.InBox);
                    List <string> uidList       = new List <string>();
                    const int     messageNumber = 5;
                    for (int i = 0; i < messageNumber; i++)
                    {
                        MailMessage message = new MailMessage(
                            "*****@*****.**",
                            "*****@*****.**",
                            "EMAILNET-35226 - " + Guid.NewGuid(),
                            "EMAILNET-35226 Add ability in ImapClient to delete messages and change flags for set of messages");
                        string uid = client.AppendMessage(message);
                        uidList.Add(uid);
                    }

                    // Now verify that all the messages have been appended to the mailbox
                    ImapMessageInfoCollection messageInfoCol = null;
                    messageInfoCol = client.ListMessages();
                    Console.WriteLine(messageInfoCol.Count);

                    // Bulk Delete Messages and  Verify that the messages are deleted
                    client.DeleteMessages(uidList, true);
                    client.CommitDeletes();
                    messageInfoCol = null;
                    messageInfoCol = client.ListMessages();
                    Console.WriteLine(messageInfoCol.Count);
                }
                finally
                {
                }
            }
            //ExStart:DeleteMultipleMessages
        }
Пример #11
0
        public static void Run()
        {
            try
            {
                // Connect to the Gmail server
                ImapClient imap = new ImapClient("imap.gmail.com", 993, "*****@*****.**", "pwd");

                // ExStart:SaveGmailMessages
                // Gets the message info collection and Download each message
                ImapMessageInfoCollection list = imap.ListMessages();
                for (int i = 0; i < list.Count; i++)
                {
                    // Save the message as an EML file
                    imap.SaveMessage(list[i].UniqueId, list[i].UniqueId + "_out.eml");
                }
                // ExEnd:SaveGmailMessages
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #12
0
        public static void Run()
        {
            //ExStart: 1
            ImapClient imapClient = new ImapClient();

            imapClient.Host                = "<HOST>";
            imapClient.Port                = 993;
            imapClient.Username            = "******";
            imapClient.Password            = "******";
            imapClient.SupportedEncryption = EncryptionProtocols.Tls;
            imapClient.SecurityOptions     = SecurityOptions.SSLImplicit;

            ImapMessageInfoCollection messageInfoCol = imapClient.ListMessages();

            foreach (ImapMessageInfo imapMessageInfo in messageInfoCol)
            {
                Console.WriteLine("ListUnsubscribe Header: " + imapMessageInfo.ListUnsubscribe);
            }
            //ExEnd: 1

            Console.WriteLine("GetListUnsubscribeHeader executed successfully.");
        }
Пример #13
0
        public static void Run()
        {
            // ExStart:SavingMessagesFromIMAPServer
            // The path to the file directory.
            string dataDir = RunExamples.GetDataDir_IMAP();

            // Create an imapclient with host, user and password
            ImapClient client = new ImapClient("localhost", "user", "password");

            // Select the inbox folder and Get the message info collection
            client.SelectFolder(ImapFolderInfo.InBox);
            ImapMessageInfoCollection list = client.ListMessages();

            // Download each message
            for (int i = 0; i < list.Count; i++)
            {
                // Save the message in MSG format
                MailMessage message = client.FetchMessage(list[i].UniqueId);
                message.Save(dataDir + list[i].UniqueId + "_out.msg", SaveOptions.DefaultMsgUnicode);
            }
            // ExEnd:SavingMessagesFromIMAPServer
        }
Пример #14
0
        public static void Run()
        {
            // ExStart:ConnectExchangeServerUsingIMAP
            // Connect to Exchange Server using ImapClient class
            ImapClient imapClient = new ImapClient("ex07sp1", "Administrator", "Evaluation1");

            imapClient.SecurityOptions = SecurityOptions.Auto;

            // Select the Inbox folder
            imapClient.SelectFolder(ImapFolderInfo.InBox);

            // Get the list of messages
            ImapMessageInfoCollection msgCollection = imapClient.ListMessages();

            foreach (ImapMessageInfo msgInfo in msgCollection)
            {
                Console.WriteLine(msgInfo.Subject);
            }
            // Disconnect from the server
            imapClient.Dispose();
            // ExEnd:ConnectExchangeServerUsingIMAP
        }
Пример #15
0
        public override int ListMessagesInFolder(ref GridView gridView, string folderUri, string searchText)
        {
            try
            {
                Email.MailQuery mQuery           = Common.GetMailQuery(searchText);
                ImapFolderInfo  folderInfoStatus = client.ListFolder(folderUri);
                client.SelectFolder(folderUri);
                ImapMessageInfoCollection msgInfoColl = null;
                if (mQuery == null)
                {
                    msgInfoColl = client.ListMessages(Common.MaxNumberOfMessages);
                }
                else
                {
                    msgInfoColl = client.ListMessages(mQuery, Common.MaxNumberOfMessages);
                }

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

                messagesList = (from msg in msgInfoColl
                                orderby msg.Date descending
                                select new Message()
                {
                    UniqueUri = msg.UniqueId,
                    Date = Common.FormatDate(msg.Date),
                    Subject = Common.FormatSubject(msg.Subject),
                    From = Common.FormatSender(msg.From)
                }).ToList();

                gridView.DataSource = messagesList;
                gridView.DataBind();

                return(msgInfoColl.Count);
            }
            catch (Exception) { }

            return(0);
        }
Пример #16
0
        public static void Run()
        {
            //ExStart: 1
            ImapClient imapClient = new ImapClient();

            imapClient.Host                = "<HOST>";
            imapClient.Port                = 993;
            imapClient.Username            = "******";
            imapClient.Password            = "******";
            imapClient.SupportedEncryption = EncryptionProtocols.Tls;
            imapClient.SecurityOptions     = SecurityOptions.SSLImplicit;

            ImapQueryBuilder imapQueryBuilder = new ImapQueryBuilder();

            imapQueryBuilder.HasNoFlags(ImapMessageFlags.IsRead); /* get unread messages. */
            MailQuery query = imapQueryBuilder.GetQuery();

            imapClient.ReadOnly = true;
            imapClient.SelectFolder("Inbox");
            ImapMessageInfoCollection messageInfoCol = imapClient.ListMessages(query);

            Console.WriteLine("Initial Unread Count: " + messageInfoCol.Count());
            if (messageInfoCol.Count() > 0)
            {
                imapClient.FetchMessage(messageInfoCol[0].SequenceNumber);

                messageInfoCol = imapClient.ListMessages(query);
                // This count will be equal to the initial count
                Console.WriteLine("Updated Unread Count: " + messageInfoCol.Count());
            }
            else
            {
                Console.WriteLine("No unread messages found");
            }
            //ExEnd: 1

            Console.WriteLine("ImapReadOnlyMode executed successfully.");
        }
        public static void Run()
        {
            // The path to the File directory.
            string dataDir = RunExamples.GetDataDir_IMAP();

            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();

            // Specify host, username, password, Port and SecurityOptions for your client
            client.Host            = "imap.gmail.com";
            client.Username        = "******";
            client.Password        = "******";
            client.Port            = 993;
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                // ExStart:FetchEmailMessagesFromIMAPServer
                // Select the inbox folder and Get the message info collection
                client.SelectFolder(ImapFolderInfo.InBox);
                ImapMessageInfoCollection list = client.ListMessages();

                // Download each message
                for (int i = 0; i < list.Count; i++)
                {
                    // Save the EML file locally
                    client.SaveMessage(list[i].UniqueId, dataDir + list[i].UniqueId + ".eml");
                }
                // ExEnd:FetchEmailMessagesFromIMAPServer

                // Disconnect to the remote IMAP server
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
        }
Пример #18
0
        public static void Run()
        {
            // ExStart:ListMessagesWithMaximumNumberOfMessages
            // Create an imapclient with host, user and password
            ImapClient client = new ImapClient("localhost", "user", "password");

            // Select the inbox folder and Get the message info collection
            ImapQueryBuilder builder = new ImapQueryBuilder();
            MailQuery        query   =
                builder.Or(
                    builder.Or(
                        builder.Or(
                            builder.Or(
                                builder.Subject.Contains(" (1) "),
                                builder.Subject.Contains(" (2) ")),
                            builder.Subject.Contains(" (3) ")),
                        builder.Subject.Contains(" (4) ")),
                    builder.Subject.Contains(" (5) "));
            ImapMessageInfoCollection messageInfoCol4 = client.ListMessages(query, 4);

            Console.WriteLine((messageInfoCol4.Count == 4) ? "Success" : "Failure");
            // ExEnd:ListMessagesWithMaximumNumberOfMessages
        }
Пример #19
0
        public static void Run()
        {
            // ExStart:ListingMIMEMessageIdInImapMessageInfo
            ImapClient client = new ImapClient();

            client.Host     = "domain.com";
            client.Username = "******";
            client.Password = "******";

            try
            {
                ImapMessageInfoCollection messageInfoCol = client.ListMessages("Inbox");
                foreach (ImapMessageInfo info in messageInfoCol)
                {
                    // Display MIME Message ID
                    Console.WriteLine("Message Id = " + info.MessageId);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            // ExEnd:ListingMIMEMessageIdInImapMessageInfo
        }
        public static void Run()
        {
            // Connect and log in to IMAP
            const string host     = "host";
            const int    port     = 143;
            const string username = "******";
            const string password = "******";
            ImapClient   client   = new ImapClient(host, port, username, password);

            try
            {
                client.SelectFolder("Inbox");

                // ExStart:CaseSensitiveEmailsFiltering
                // Set conditions, Subject contains "Newsletter", Emails that arrived today
                ImapQueryBuilder builder = new ImapQueryBuilder();
                builder.Subject.Contains("Newsletter", true);
                builder.InternalDate.On(DateTime.Now);
                MailQuery query = builder.GetQuery();
                // ExEnd:CaseSensitiveEmailsFiltering

                // Get list of messages
                ImapMessageInfoCollection messages = client.ListMessages(query);
                foreach (ImapMessageInfo info in messages)
                {
                    Console.WriteLine("Message Id: " + info.MessageId);
                }

                // Disconnect from IMAP
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #21
0
        public static void Run()
        {
            // ExStart:1
            ImapClient imapClient = new ImapClient();

            imapClient.Host                = "<HOST>";
            imapClient.Port                = 993;
            imapClient.Username            = "******";
            imapClient.Password            = "******";
            imapClient.SupportedEncryption = EncryptionProtocols.Tls;
            imapClient.SecurityOptions     = SecurityOptions.SSLImplicit;

            PageSettings pageSettings = new PageSettings {
                AscendingSorting = false
            };
            ImapPageInfo pageInfo = imapClient.ListMessagesByPage(5, pageSettings);
            ImapMessageInfoCollection messages = pageInfo.Items;

            foreach (ImapMessageInfo message in messages)
            {
                Console.WriteLine(message.Subject + " -> " + message.Date.ToString());
            }
            // ExEnd:1
        }
        static void Run()
        {
            // ExStart:SearchWithPagingSupport
            ///<summary>
            /// This example shows how to search for messages using ImapClient of the API with paging support
            /// Introduced in Aspose.Email for .NET 6.4.0
            ///</summary>
            using (ImapClient client = new ImapClient("host.domain.com", 84, "username", "password"))
            {
                try
                {
                    // Append some test messages
                    int         messagesNum  = 12;
                    int         itemsPerPage = 5;
                    MailMessage message      = null;
                    for (int i = 0; i < messagesNum; i++)
                    {
                        message = new MailMessage(
                            "*****@*****.**",
                            "*****@*****.**",
                            "EMAILNET-35128 - " + Guid.NewGuid(),
                            "111111111111111");
                        client.AppendMessage(ImapFolderInfo.InBox, message);
                    }
                    string body = "2222222222222";
                    for (int i = 0; i < messagesNum; i++)
                    {
                        message = new MailMessage(
                            "*****@*****.**",
                            "*****@*****.**",
                            "EMAILNET-35128 - " + Guid.NewGuid(),
                            body);
                        client.AppendMessage(ImapFolderInfo.InBox, message);
                    }

                    ImapQueryBuilder iqb = new ImapQueryBuilder();
                    iqb.Body.Contains(body);
                    MailQuery query = iqb.GetQuery();

                    client.SelectFolder(ImapFolderInfo.InBox);
                    ImapMessageInfoCollection totalMessageInfoCol = client.ListMessages(query);
                    Console.WriteLine(totalMessageInfoCol.Count);

                    //////////////////////////////////////////////////////

                    List <ImapPageInfo> pages    = new List <ImapPageInfo>();
                    ImapPageInfo        pageInfo = client.ListMessagesByPage(ImapFolderInfo.InBox, query, itemsPerPage);
                    pages.Add(pageInfo);
                    while (!pageInfo.LastPage)
                    {
                        pageInfo = client.ListMessagesByPage(ImapFolderInfo.InBox, query, pageInfo.NextPage);
                        pages.Add(pageInfo);
                    }
                    int retrievedItems = 0;
                    foreach (ImapPageInfo folderCol in pages)
                    {
                        retrievedItems += folderCol.Items.Count;
                    }
                }
                finally
                {
                }
            }
            // ExEnd: SearchWithPagingSupport
        }
Пример #23
0
        public static void Run()
        {
            // Connect and log in to POP3
            const string host     = "host";
            const int    port     = 143;
            const string username = "******";
            const string password = "******";
            ImapClient   client   = new ImapClient(host, port, username, password);

            try
            {
                // ExStart:GetEmailsWithTodayDate
                // Emails that arrived today
                MailQueryBuilder builder = new MailQueryBuilder();
                builder.InternalDate.On(DateTime.Now);
                // ExEnd:GetEmailsWithTodayDate

                // Build the query and Get list of messages
                MailQuery query = builder.GetQuery();
                ImapMessageInfoCollection messages = client.ListMessages(query);
                Console.WriteLine("Imap: " + messages.Count + " message(s) found.");

                builder = new MailQueryBuilder();

                // ExStart:GetEmailsOverDateRange
                // Emails that arrived in last 7 days
                builder.InternalDate.Before(DateTime.Now);
                builder.InternalDate.Since(DateTime.Now.AddDays(-7));
                // ExEnd:GetEmailsOverDateRange

                // Build the query and Get list of messages
                query    = builder.GetQuery();
                messages = client.ListMessages(query);
                Console.WriteLine("Imap: " + messages.Count + " message(s) found.");

                builder = new MailQueryBuilder();

                // ExStart:GetSpecificSenderEmails
                // Get emails from specific sender
                builder.From.Contains("[email protected]");
                // ExEnd:GetSpecificSenderEmails

                // Build the query and Get list of messages
                query    = builder.GetQuery();
                messages = client.ListMessages(query);
                Console.WriteLine("Imap: " + messages.Count + " message(s) found.");

                builder = new MailQueryBuilder();

                // ExStart:GetSpecificDomainEmails
                // Get emails from specific domain
                builder.From.Contains("SpecificHost.com");
                // ExEnd:GetSpecificDomainEmails

                // Build the query and Get list of messages
                query    = builder.GetQuery();
                messages = client.ListMessages(query);
                Console.WriteLine("Imap: " + messages.Count + " message(s) found.");

                builder = new MailQueryBuilder();

                // ExStart:GetSpecificRecipientEmails
                // Get emails sent to specific recipient
                builder.To.Contains("recipient");
                // ExEnd:GetSpecificRecipientEmails

                //ExStart: GetMessagesWithCustomFlags
                ImapQueryBuilder queryBuilder = new ImapQueryBuilder();

                queryBuilder.HasFlags(ImapMessageFlags.Keyword("custom1"));

                queryBuilder.HasNoFlags(ImapMessageFlags.Keyword("custom2"));
                //ExEnd: GetMessagesWithCustomFlags

                // Build the query and Get list of messages
                query    = builder.GetQuery();
                messages = client.ListMessages(query);
                Console.WriteLine("Imap: " + messages.Count + " message(s) found.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #24
0
        private void readInbox(ImapClient client)
        {
            Dictionary <string, clsFileList> convertFiles = new Dictionary <string, clsFileList>();

            // select the inbox folder
            client.SelectFolder(ImapFolderInfo.InBox);

            // get the message info collection
            ImapMessageInfoCollection list = client.ListMessages();

            // iterate through the messages and retrieve one by one
            // TO DO: this example code might be able to be rewritten as a foreach(ImapMessageInfo...
            // will still need to do the client.FetchMessage though.
            for (int i = 1; i <= list.Count; i++)
            {
                // create object of type MailMessage
                MailMessage msg;

                Utils.WriteToLog(Utils.LogSeverity.Info, processName, String.Format("Reading message number {0} of {1}", i, list.Count));

                msg = client.FetchMessage(i);

                if (!list[i - 1].Readed)
                {
                    Utils.WriteToLog(Utils.LogSeverity.Info, processName, "Message not read");

                    foreach (Attachment attachedFile in msg.Attachments)
                    {
                        Utils.WriteToLog(Utils.LogSeverity.Info, processName, "Extracting attachement");

                        extractAttachment(convertFiles, attachedFile);

                        Utils.WriteToLog(Utils.LogSeverity.Info, processName, "Finished extracting attachement");

                        //FileStream writeFile = new FileStream(destinationFolder + @"\" + attachedFile.Name, FileMode.Create);
                        //attachedFile.SaveRawContent(writeFile);
                        //writeFile.Close();

                        //Utils.WriteToLog(Utils.LogSeverity.Info, processName, "Downloaded file: " + destinationFolder + @"\" + attachedFile.Name);
                        //if (immediateExcelExtract == "1" && (attachedFile.Name.ToLower().EndsWith("xls") || attachedFile.Name.ToLower().EndsWith("xlsx")))
                        //{
                        //    convertFiles.Add(destinationFolder + @"\" + attachedFile.Name, new clsFileList { FullFilePath = destinationFolder + @"\" + attachedFile.Name });
                        //}
                    }

                    Utils.WriteToLog(Utils.LogSeverity.Info, processName, "Immediate extraction, if required");



                    //if (immediateExcelExtract == "1")
                    //{
                    //    // In immediate mode we save the contents of each workbook
                    //    // to the current folder
                    //    // Finally delete all the original xls files
                    //    cf.ConvertExcelToCSV(convertFiles, destinationFolder, true);
                    //}

                    Utils.WriteToLog(Utils.LogSeverity.Info, processName, "Changing email status");

                    client.ChangeMessageFlags(i, Aspose.Network.Imap.MessageFlags.Readed);

                    Utils.WriteToLog(Utils.LogSeverity.Info, processName, "Finished changing email status");
                }
            }
        }