Example #1
0
        public static void Run()
        {
            try
            {
                // ExStart:SendIMAPasynchronousEmail
                // Create an imapclient with host, user and password
                ImapClient client = new ImapClient();
                client.Host     = "domain.com";
                client.Username = "******";
                client.Password = "******";
                client.SelectFolder("InBox");

                ImapMessageInfoCollection messages = client.ListMessages();
                IAsyncResult res1 = client.BeginFetchMessage(messages[0].UniqueId);
                IAsyncResult res2 = client.BeginFetchMessage(messages[1].UniqueId);
                MailMessage  msg1 = client.EndFetchMessage(res1);
                MailMessage  msg2 = client.EndFetchMessage(res2);

                // ExEnd:SendIMAPasynchronousEmail

                // ExStart:SendIMAPasynchronousEmailThreadPool
                List <MailMessage> List = new List <MailMessage>();
                ThreadPool.QueueUserWorkItem(delegate(object o)
                {
                    client.SelectFolder("folderName");
                    ImapMessageInfoCollection messageInfoCol = client.ListMessages();
                    foreach (ImapMessageInfo messageInfo in messageInfoCol)
                    {
                        List.Add(client.FetchMessage(messageInfo.UniqueId));
                    }
                });
                // ExEnd:SendIMAPasynchronousEmailThreadPool

                // ExStart:SendIMAPasynchronousEmailThreadPool1
                List <MailMessage> List1 = new List <MailMessage>();
                ThreadPool.QueueUserWorkItem(delegate(object o)
                {
                    using (IDisposable connection = client.CreateConnection())
                    {
                        client.SelectFolder("FolderName");
                        ImapMessageInfoCollection messageInfoCol =
                            client.ListMessages();
                        foreach (ImapMessageInfo messageInfo in messageInfoCol)
                        {
                            List1.Add(client.FetchMessage(messageInfo.UniqueId));
                        }
                    }
                });
                // ExEnd:SendIMAPasynchronousEmailThreadPool1
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                throw;
            }
        }
        public static void Run()
        {
            try
            {

            // ExStart:SendIMAPasynchronousEmail
            // Create an imapclient with host, user and password
            ImapClient client = new ImapClient();
            client.Host = "domain.com";
            client.Username = "******";
            client.Password = "******";
            client.SelectFolder("InBox");

            ImapMessageInfoCollection messages = client.ListMessages();
            IAsyncResult res1 = client.BeginFetchMessage(messages[0].UniqueId);
            IAsyncResult res2 = client.BeginFetchMessage(messages[1].UniqueId);
            MailMessage msg1 = client.EndFetchMessage(res1);
            MailMessage msg2 = client.EndFetchMessage(res2);

            // ExEnd:SendIMAPasynchronousEmail

            // ExStart:SendIMAPasynchronousEmailThreadPool
            List<MailMessage> List = new List<MailMessage>();
            ThreadPool.QueueUserWorkItem(delegate(object o)
            {
                client.SelectFolder("folderName");
                ImapMessageInfoCollection messageInfoCol = client.ListMessages();
                foreach (ImapMessageInfo messageInfo in messageInfoCol)
                {
                    List.Add(client.FetchMessage(messageInfo.UniqueId));
                }
            });
            // ExEnd:SendIMAPasynchronousEmailThreadPool

            // ExStart:SendIMAPasynchronousEmailThreadPool1
            List<MailMessage> List1 = new List<MailMessage>();
            ThreadPool.QueueUserWorkItem(delegate(object o)
            {
                using (IDisposable connection = client.CreateConnection())
                {
                    client.SelectFolder("FolderName");
                    ImapMessageInfoCollection messageInfoCol =
               client.ListMessages();
                    foreach (ImapMessageInfo messageInfo in messageInfoCol)
                        List1.Add(client.FetchMessage(messageInfo.UniqueId));
                }
            });
            // ExEnd:SendIMAPasynchronousEmailThreadPool1
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                throw;
            }
        }
Example #3
0
        public static void Run()
        {
            string dataDir = RunExamples.GetDataDir_Exchange();

            try
            {
                ImapClient imapClient = new ImapClient("ex07sp1", "Administrator", "Evaluation1");
                imapClient.SecurityOptions = SecurityOptions.Auto;

                // ExStart:SaveMessagesUsingIMAP
                // Select the Inbox folder
                imapClient.SelectFolder(ImapFolderInfo.InBox);
                // Get the list of messages
                ImapMessageInfoCollection msgCollection = imapClient.ListMessages();
                foreach (ImapMessageInfo msgInfo in msgCollection)
                {
                    // Fetch the message from inbox using its SequenceNumber from msgInfo
                    MailMessage message = imapClient.FetchMessage(msgInfo.SequenceNumber);

                    // Save the message to disc now
                    message.Save(dataDir + msgInfo.SequenceNumber + "_out.msg", SaveOptions.DefaultMsgUnicode);
                }
                // ExEnd:SaveMessagesUsingIMAP
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    protected void gvMessages_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DisplayMessage")
        {
            pnlMessage.Visible = true;
            string msgSequenceNumber = e.CommandArgument.ToString();

            try
            {
                // initialize imap client
                ImapClient client = new ImapClient();
                client.Host = txtHost.Text;
                client.Port = int.Parse(txtPort.Text);
                client.Username = txtUsername.Text;
                client.Password = Session["Password"].ToString();

                // SSL Settings
                if (chSSL.Checked == true)
                {
                    client.EnableSsl = true;
                    client.SecurityMode = ImapSslSecurityMode.Implicit;
                }

                // connect to pop3 server and login
                client.Connect(true);
                client.SelectFolder(ImapFolderInfo.InBox);
                lblMessage.ForeColor = Color.Green;
                lblMessage.Text = "Successfully connected to Imap Mail server.<br><hr>";

                // get the message
                MailMessage msg = client.FetchMessage(int.Parse(msgSequenceNumber));
                // sender name and address
                litFrom.Text = msg.From[0].DisplayName + " <" + msg.From[0].Address + ">";
                // to addresses
                litTo.Text = "";
                foreach (MailAddress address in msg.To)
                {
                    litTo.Text += address.DisplayName + " <" + address.Address + "> , ";
                }
                // cc addresses
                litCc.Text = "";
                foreach (MailAddress address in msg.CC)
                {
                    litCc.Text += address.DisplayName + " <" + address.Address + "> , ";
                }
                // subject
                litSubject.Text = msg.Subject;
                litBody.Text = msg.HtmlBody;

                client.Disconnect();
            }
            catch (Exception ex)
            {
                lblMessage.ForeColor = Color.Red;
                lblMessage.Text = "Error: " + ex.Message;
            }
        }
    }
    private void DownloadFile(string msgSequenceNumber, string format)
    {
        try
        {
            // initialize imap client
            ImapClient client = new ImapClient();
            client.Host = txtHost.Text;
            client.Port = int.Parse(txtPort.Text);
            client.Username = txtUsername.Text;
            client.Password = Session["Password"].ToString();

            // SSL Settings
            if (chSSL.Checked == true)
            {
                client.EnableSsl = true;
                client.SecurityMode = ImapSslSecurityMode.Implicit;
            }

            // connect to imap server and login
            client.Connect(true);
            client.SelectFolder(ImapFolderInfo.InBox);
            lblMessage.ForeColor = Color.Green;
            lblMessage.Text = "Successfully connected to Imap Mail server.<br><hr>";

            // get the message
            MemoryStream stream = new MemoryStream();
            MailMessage msg = client.FetchMessage(int.Parse(msgSequenceNumber));
            if (format == "eml")
                msg.Save(stream, MessageFormat.Eml);
            else
                msg.Save(stream, MessageFormat.Msg);
            stream.Position = 0;
            byte[] msgBytes = new byte[stream.Length];
            stream.Read(msgBytes, 0, (int)stream.Length);

            client.Disconnect();

            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("Content-Length", msgBytes.Length.ToString());
            Response.AddHeader("Content-Disposition", "attachment; filename=Message." + format);
            Response.ContentType = "application/octet-stream";
            Response.BinaryWrite(msgBytes);
            Response.End();

        }
        catch (Exception ex)
        {
            lblMessage.ForeColor = Color.Red;
            lblMessage.Text = "Error: " + ex.Message;
        }
    }
        /// <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) { }
        }
        /// Recursive method to get messages from folders and sub-folders
        private static void ListMessagesInFolder(ImapFolderInfo folderInfo, string rootFolder, ImapClient client)
        {
            // Create the folder in disk (same name as on IMAP server)
            string currentFolder = RunExamples.GetDataDir_IMAP();
            Directory.CreateDirectory(currentFolder);

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

                // Select the current folder and List messages
                client.SelectFolder(folderInfo.Name);
                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 and Save the message in MSG format
                    string fileName = msgInfo.Subject.Replace(":", " ").Replace("?", " ");
                    MailMessage msg = client.FetchMessage(msgInfo.SequenceNumber);
                    msg.Save(currentFolder + "\\" + fileName + "-" + msgInfo.SequenceNumber + ".msg", 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) { }
            // ExEnd:ReadMessagesRecursively
        }
Example #8
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
        }
Example #9
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.");
        }
Example #10
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");
                }
            }
        }