Summary description for ImapClient
        public static void Run()
        {
            // ExStart:InternalDateFilter
            // 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);
            client.SelectFolder("Inbox");

            // Set conditions, Subject contains "Newsletter", Emails that arrived today
            ImapQueryBuilder builder = new ImapQueryBuilder();
            builder.Subject.Contains("Newsletter");
            builder.InternalDate.On(DateTime.Now);
            // Build the query and Get list of messages
            MailQuery query = builder.GetQuery();
            ImapMessageInfoCollection messages = client.ListMessages(query);
            foreach (ImapMessageInfo info in messages)
            {
                Console.WriteLine("Internal Date: " + info.InternalDate);
            }
            // Disconnect from IMAP
            client.Dispose();
            // ExEnd:InternalDateFilter
        }
        public static void Run()
        {
            //ExStart:DeleteSingleMessage
            using (ImapClient client = new ImapClient("exchange.aspose.com", "username", "password"))
            {
                try
                {
                    Console.WriteLine(client.UidPlusSupported.ToString());
                    // Append some test messages
                    client.SelectFolder(ImapFolderInfo.InBox);
                    MailMessage message = new MailMessage("*****@*****.**", "*****@*****.**", "EMAILNET-35227 - " + Guid.NewGuid(), "EMAILNET-35227 Add ability in ImapClient to delete message");
                    string emailId = client.AppendMessage(message);

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

                    // Select the inbox folder and Delete message
                    client.SelectFolder(ImapFolderInfo.InBox);
                    client.DeleteMessage(emailId);
                    client.CommitDeletes();
                }
                finally
                {

                }
            }
            //ExEnd:DeleteSingleMessage
        }
        public static void Run()
        {
            // ExStart:SupportIMAPIdleCommand
            // Connect and log in to IMAP 
            ImapClient client = new ImapClient("imap.domain.com", "username", "password");

            ManualResetEvent manualResetEvent = new ManualResetEvent(false);
            ImapMonitoringEventArgs eventArgs = null;
            client.StartMonitoring(delegate(object sender, ImapMonitoringEventArgs e)
            {
                eventArgs = e;
                manualResetEvent.Set();
            });
            Thread.Sleep(2000);
            SmtpClient smtpClient = new SmtpClient("exchange.aspose.com", "username", "password");
            smtpClient.Send(new MailMessage("*****@*****.**", "*****@*****.**", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command"));
            manualResetEvent.WaitOne(10000);
            manualResetEvent.Reset();
            Console.WriteLine(eventArgs.NewMessages.Length);
            Console.WriteLine(eventArgs.DeletedMessages.Length);
            client.StopMonitoring("Inbox");
            smtpClient.Send(new MailMessage("*****@*****.**", "*****@*****.**", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command"));
            manualResetEvent.WaitOne(5000);
            // ExEnd:SupportIMAPIdleCommand
        }
        public static void Run()
        {
            //ExStart:DeletingFolders
            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();

            // Specify host, username and password, and set port for your client
            client.Host = "imap.gmail.com";
            client.Username = "******";
            client.Password = "******";
            client.Port = 993;
            client.SecurityOptions = SecurityOptions.Auto;
            try
            {
                // Rename a folder and Disconnect to the remote IMAP server
                client.DeleteFolder("Client");
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
            //ExEnd:DeletingFolders
            Console.WriteLine(Environment.NewLine + "Deleted folders on IMAP server.");
        }
        public static void Run()
        {
            //ExStart:AddingNewMessage
            // Create a message
            MailMessage msg = new MailMessage("*****@*****.**", "*****@*****.**", "subject", "message");

            // 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
            {
                // Subscribe to the Inbox folder, Append the newly created message and Disconnect to the remote IMAP server
                client.SelectFolder(ImapFolderInfo.InBox);
                client.SubscribeFolder(client.CurrentFolder.Name);
                client.AppendMessage(client.CurrentFolder.Name, msg);
                Console.WriteLine("New Message Added Successfully");
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
            Console.WriteLine(Environment.NewLine + "Added new message on IMAP server.");
            //ExEnd:AddingNewMessage
        }
Ejemplo n.º 6
0
        private List<string> CheckForMessages()
        {
            var messages = new List<string>();

            _client = new ImapClient(_IMAPClientUri, true);
            if (_client.Connect() && _client.Login(_IMAPUsername, _IMAPPassword))
            {
                try
                {
                    var keyword = _subjectKeyword;                    
                    var emails = _client.Folders.Inbox.Search(string.Format("UNSEEN SUBJECT \"{0}\"", keyword), ImapX.Enums.MessageFetchMode.Full);
                    Console.WriteLine(string.Format("{0} emails", emails.Count()));
                    foreach (var email in emails)
                    {
                        messages.Add(email.Body.Text);
                        email.Remove();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                finally
                {
                    _client.Logout();
                    _client.Disconnect();                    
                }
            }
            else
            {
                Console.WriteLine("Bad email login");
            }
            return messages;
        }
        public static void Run()
        {
            //ExStart:SSLEnabledIMAPServer
            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();
            // Specify host, username and password, Port and SecurityOptions for your client
            client.Host = "imap.gmail.com";
            client.Username = "******";
            client.Password = "******";
            client.Port = 993;
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                Console.WriteLine("Logged in to the IMAP server");
                // Disconnect to the remote IMAP server
                client.Dispose();
                Console.WriteLine("Disconnected from the IMAP server");
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
            //ExEnd:SSLEnabledIMAPServer
            Console.WriteLine(Environment.NewLine + "Connected to IMAP server with SSL.");
        }
        // ExStart:ReadMessagesRecursively
        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
            {
                // The root folder (which will be created on disk) consists of host and username
                string rootFolder = client.Host + "-" + client.Username;

                // Create the root folder and List all the folders from IMAP server
                Directory.CreateDirectory(rootFolder);
                ImapFolderInfoCollection folderInfoCollection = client.ListFolders();
                foreach (ImapFolderInfo folderInfo in folderInfoCollection)
                {
                    // Call the recursive method to read messages and get sub-folders
                    ListMessagesInFolder(folderInfo, rootFolder, client);
                }
                // Disconnect to the remote IMAP server
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }

            Console.WriteLine(Environment.NewLine + "Downloaded messages recursively from IMAP server.");
        }
        public static void Run()
        {
            //ExStart:SettingMessageFlags
            // 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
            {
                Console.WriteLine("Logged in to the IMAP server");
                // Mark the message as read and Disconnect to the remote IMAP server
                client.ChangeMessageFlags(1, ImapMessageFlags.IsRead);
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
            //ExEnd:SettingMessageFlags
            Console.WriteLine(Environment.NewLine + "Set message flags from IMAP server.");
        }
    protected void brnSendEmail_Click(object sender, EventArgs e)
    {
        lblMessage.Text = "";

        try
        {
            // initialize imap client
            ImapClient client = new ImapClient();
            client.Host = txtHost.Text;
            client.Port = int.Parse(txtPort.Text);
            client.Username = txtUsername.Text;
            client.Password = txtPassword.Text;

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

            client.Disconnect();
        }
        catch (Exception ex)
        {
            lblMessage.ForeColor = Color.Red;
            lblMessage.Text = "Error: " + ex.Message;
        }
    }
 public GMailMessageLabelCollection(ImapClient client, Message message)
     : base(client, message)
 {
     AddType = "+X-GM-LABELS";
     RemoveType = "-X-GM-LABELS";
     IsUTF7 = true;
     AddQuotes = true;
 }
Ejemplo n.º 12
0
        private IEnumerable<Chat> ProcessChats(ImapClient client)
        {
            var folder = client.GetChatsFolder();

            return Enumerable.Range(_startIndex, _stopIndex - _startIndex)
                .Where(i => i < folder.Messages.Count)
                .Select(i => ChatFromImapMessage(folder.Messages[i]));
        }
Ejemplo n.º 13
0
 internal bool GmailAuthenticate(string username, string password)
 {
     var client = new ImapClient("imap.gmail.com", 993, true, true);
     client.Connect();
     bool result = client.Login(username,password);
     if (result) return true;
     else return false;
 }
    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;
            }
        }
    }
Ejemplo n.º 15
0
 public void getFolders(string canvasid, int windowid)
 {
     ImapClient imp = new ImapClient(ccl.InputParams[2].ToString(), 993, ccl.InputParams[0].ToString(), ccl.InputParams[1].ToString(), true);
     List<string> mailboxes = imp.GetAllFolders();
     foreach(string mb in mailboxes){
         parameters.Add(mb);
     }
     imp.Logout();
 }
Ejemplo n.º 16
0
 public void getMailMessage(string canvasid, int windowid)
 {
     ImapClient imp = new ImapClient(ccl.InputParams[2].ToString(), 993, ccl.InputParams[0].ToString(), ccl.InputParams[1].ToString(), true);
     List<object> arlmsg = new List<object>();
     arlmsg.Add("");
     arlmsg.Add("");
     arlmsg.Add("");
     arlmsg.Add(XmlEscape(imp.GetMessageBody(ccl.InputParams[3].ToString(), ccl.InputParams[4].ToString())));
     parameters.Add(arlmsg);
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Connects to the imap server.
 /// </summary>
 /// <param name="login">Login credidentials containing username and password of user</param>
 /// <param name="server">Server address to connect to</param>
 public void Connect(LoginCred login, string server)
 {
     imapc = new ImapClient(server, true);
       if (imapc.Connect())
     if (imapc.Login(login.Username, login.Password))
     {
       blnConnected = true;
       imapc.Behavior.AutoPopulateFolderMessages = true;
     }
 }
        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;
            }
        }
Ejemplo n.º 19
0
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_IMAP();
            string dstEmail = dataDir + "1234.eml";

            // Create a message
            Aspose.Email.Mail.MailMessage msg;
            msg = new Aspose.Email.Mail.MailMessage(
            "*****@*****.**",
            "*****@*****.**",
            "subject",
            "message"
            );

            //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
            {
                // Subscribe to the Inbox folder
                client.SelectFolder(ImapFolderInfo.InBox);
                client.SubscribeFolder(client.CurrentFolder.Name);

                // Append the newly created message
                client.AppendMessage(client.CurrentFolder.Name, msg);

                System.Console.WriteLine("New Message Added Successfully");

                //Disconnect to the remote IMAP server
                client.Disconnect();

            }
            catch (Exception ex)
            {
                System.Console.Write(Environment.NewLine + ex.ToString());
            }

            Console.WriteLine(Environment.NewLine + "Added new message on IMAP server.");
        }
Ejemplo n.º 20
0
        public static ImapClient FromLoginInfo(string username, string password)
        {
            var imapClient = new ImapClient("imap.gmail.com", 993, true);

            if (!imapClient.Connection())
                throw new Exception("Could not connect!");
            if (!imapClient.LogIn(username, password))
                throw new Exception("Could not log in!");

            return imapClient;
        }
        static void Run()
        { 
            // ExStart: MoveMessage
            ///<summary>
            /// This example shows how to move a message from one folder of a mailbox to another one using the ImapClient API of Aspose.Email for .NET
            /// Available from Aspose.Email for .NET 6.4.0 onwards
            /// -------------- Available API Overload Members --------------
            /// Void ImapClient.MoveMessage(IConnection iConnection, int sequenceNumber, string folderName, bool commitDeletions)
            /// Void ImapClient.MoveMessage(IConnection iConnection, string uniqueId, string folderName, bool commitDeletions)
            /// Void ImapClient.MoveMessage(int sequenceNumber, string folderName, bool commitDeletions)
            /// Void ImapClient.MoveMessage(string uniqueId, string folderName, bool commitDeletions)
            /// Void ImapClient.MoveMessage(IConnection iConnection, int sequenceNumber, string folderName)
            /// Void ImapClient.MoveMessage(IConnection iConnection, string uniqueId, string folderName)
            /// Void ImapClient.MoveMessage(int sequenceNumber, string folderName)
            /// Void ImapClient.MoveMessage(string uniqueId, string folderName)
            ///</summary>

            using (ImapClient client = new ImapClient("host.domain.com", 993, "username", "password"))
            {
                string folderName = "EMAILNET-35151";
                if (!client.ExistFolder(folderName))
                    client.CreateFolder(folderName);
                try
                {
                    MailMessage message = new MailMessage(
                        "*****@*****.**",
                        "*****@*****.**",
                        "EMAILNET-35151 - " + Guid.NewGuid(),
                        "EMAILNET-35151 ImapClient: Provide option to Move Message");
                    client.SelectFolder(ImapFolderInfo.InBox);
                    // Append the new message to Inbox folder
                    string uniqueId = client.AppendMessage(ImapFolderInfo.InBox, message);
                    ImapMessageInfoCollection messageInfoCol1 = client.ListMessages();
                    Console.WriteLine(messageInfoCol1.Count);
                    // Now move the message to the folder EMAILNET-35151
                    client.MoveMessage(uniqueId, folderName);
                    client.CommitDeletes();
                    // Verify that the message was moved to the new folder
                    client.SelectFolder(folderName);
                    messageInfoCol1 = client.ListMessages();
                    Console.WriteLine(messageInfoCol1.Count);
                    // Verify that the message was moved from the Inbox
                    client.SelectFolder(ImapFolderInfo.InBox);
                    messageInfoCol1 = client.ListMessages();
                    Console.WriteLine(messageInfoCol1.Count);
                }
                finally
                {
                    try { client.DeleteFolder(folderName); }
                    catch { }
                }
            }
            // ExEnd: MoveMessage
        }
Ejemplo n.º 22
0
        //http://imapx.codeplex.com/documentation
        static void Main(string[] args)
        {
            // ApplicationTrustPolicy.TrustAll();

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

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

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

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

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

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

                    string fn = "instant_" + cbtt + "_" + pcode + "_" + DateTime.Now.ToString("MMMdyyyyHHmmssfff") + ".txt";
                    fn = Path.Combine(output_dir, fn);
                   HydrometInstantSeries.WriteToHydrometFile(s, cbtt, pcode, "hydromet", fn);
                }
            }
            else
            {
                Logger.WriteLine("connection not successful");
            }
        }
        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
            {
                // Get all folders in the currently subscribed folder
                Aspose.Email.Imap.ImapFolderInfoCollection folderInfoColl = client.ListFolders();

                // Iterate through the collection to get folder info one by one
                foreach (Aspose.Email.Imap.ImapFolderInfo folderInfo in folderInfoColl)
                {
                    // Folder name
                    Console.WriteLine("Folder name is " + folderInfo.Name);
                    ImapFolderInfo folderExtInfo = client.ListFolder(folderInfo.Name);
                    // New messages in the folder
                    Console.WriteLine("New message count: " + folderExtInfo.NewMessageCount);
                    // Check whether its readonly
                    Console.WriteLine("Is it readonly? " + folderExtInfo.ReadOnly);
                    // Total number of messages
                    Console.WriteLine("Total number of messages " + folderExtInfo.TotalMessageCount);
                }

                //Disconnect to the remote IMAP server
                client.Disconnect();

            }
            catch (Exception ex)
            {
                System.Console.Write(Environment.NewLine + ex.ToString());
            }

            Console.WriteLine(Environment.NewLine + "Getting folders information from IMAP server.");
        }
 public static void Run()
 {
     // ExStart:RetreivingServerExtensions
     // Connect and log in to IMAP
     ImapClient client = new ImapClient("imap.gmail.com", "username", "password");
     string[] getCapabilities = client.GetCapabilities();
     foreach (string getCap in getCapabilities)
     {
         Console.WriteLine(getCap);
     }
     // ExEnd:RetreivingServerExtensions
 }
        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
        }
    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;
        }
    }
Ejemplo n.º 27
0
    public static void Main(string[] args)
    {
        ImapConnection.ServerCertificateValidationCallback += delegate {
          // 適切な証明書の検証を行うように書き換えてください
          return true;
        };

        using (var client = new ImapClient(new Uri("imap://[email protected]/"))) {
          client.Connect("pass");

          Console.WriteLine("connected!!");
        }
    }
Ejemplo n.º 28
0
        private static bool Connect(ImapClient client)
        {
            if (client.Connect())
            {
                //if (client.Login(MailLogin, MailPassword))
                if (client.Login("*****@*****.**", "1597534682"))
                {
                    return true;
                }
            }

            return false;
        }
 public static void Run()
 {
     // ExStart:GetMessageIdUsingImapMessageInfo
     // 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:GetMessageIdUsingImapMessageInfo
 }
        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
            {
                // The root folder (which will be created on disk) consists of host and username
                string rootFolder = client.Host + "-" + client.Username;
                // Create the root folder
                Directory.CreateDirectory(rootFolder);

                // List all the folders from IMAP server
                ImapFolderInfoCollection folderInfoCollection = client.ListFolders();
                foreach (ImapFolderInfo folderInfo in folderInfoCollection)
                {
                    // Call the recursive method to read messages and get sub-folders
                    ListMessagesInFolder(folderInfo, rootFolder, client);
                }


                //Disconnect to the remote IMAP server
                client.Disconnect();

            }
            catch (Exception ex)
            {
                System.Console.Write(Environment.NewLine + ex.ToString());
            }

            Console.WriteLine(Environment.NewLine + "Downloaded messages recursively from IMAP server.");
        }
Ejemplo n.º 31
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string imapsite = "";
            string stmpsite = "";

            try
            {
                ImapClient ic = new ImapClient("imap.mail.ru", LoginTextBox.Text.ToString(), Passwordbx.Password.ToString(), AuthMethods.Login, 993, true);
                imapsite = "imap.mail.ru";
                stmpsite = "smtp.mail.ru";
            }
            catch
            {
                try
                {
                    ImapClient ic = new ImapClient("imap.gmail.com", LoginTextBox.Text.ToString(), Passwordbx.Password.ToString(), AuthMethods.Login, 993, true);
                    imapsite = "imap.gmail.com";
                    stmpsite = "smtp.gmail.com";
                }
                catch
                {
                    try
                    {
                        ImapClient ic = new ImapClient("imap.yandex.ru", LoginTextBox.Text.ToString(), Passwordbx.Password.ToString(), AuthMethods.Login, 993, true);
                        imapsite = "imap.yandex.ru";
                        stmpsite = "smtp.yandex.ru";
                    }
                    catch
                    {
                        try
                        {
                            ImapClient ic = new ImapClient("imap.rambler.ru", LoginTextBox.Text.ToString(), Passwordbx.Password.ToString(), AuthMethods.Login, 993, true);
                            imapsite = "imap.rambler.ru";
                            stmpsite = "smtp.rambler.ru";
                        }
                        catch
                        {
                            ContentDialog prog = new ContentDialog()
                            {
                                Title             = "Ошибка",
                                Content           = $"Произошла ошибка: Проверьте вводимые данные",
                                PrimaryButtonText = "OK"
                            };
                            await prog.ShowAsync();
                        }
                    }
                }
            }
            if (imapsite != "")
            {
                file = await folder.CreateFileAsync("UserData.xml", CreationCollisionOption.OpenIfExists);

                Stream stream2 = await file.OpenStreamForWriteAsync();

                UserData us = new UserData()
                {
                    Login = LoginTextBox.Text,
                    Pass  = Passwordbx.Password,
                    imap  = imapsite,
                    smtp  = stmpsite,
                };
                user.Add(us);
                xml2.Serialize(stream2, user);
                stream2.Close();
                this.Frame.Navigate(typeof(MainPage), user);
            }
        }
Ejemplo n.º 32
0
 public void Dispose()
 {
     imapClient?.Dispose();
     imapClient = null;
 }
        public void ReadEmails(string folder,
                               DateTime?fromDate,
                               IList <string> acceptingToAddresses,
                               IList <string> acceptingFromAddresses,
                               CancellationToken?cancel)
        {
            _emailProcessResultList = new List <EmailReadingResult>();

            using (var imap = new ImapClient(_settings.ImapHost,
                                             _settings.ImapPort,
                                             _settings.ImapUsername,
                                             _settings.ImapPassword,
                                             AuthMethod.Login,
                                             ssl: true))
            {
                //var uids = new List<uint>(ImapClient.Search(SearchCondition.SentSince(sentSince).Or(SearchCondition.GreaterThan(lastUid)), mailbox));

                //var uids = new List<uint>(ImapClient.Search(SearchCondition.From("*****@*****.**"), _mailbox));
                //var uids = new List<uint> {lastUid};// 14559 };
                //var uids = new List<uint>(ImapClient.Search(SearchCondition.SentSince(new DateTime(2013, 12, 3)).Or(SearchCondition.GreaterThan(105748)), mailbox));//.SentSince(sentSince.AddHours(-12)), mailbox));


                var sentSince = fromDate ?? _time.GetUtcTime().AddDays(-2);
                using (var db = _dbFactory.GetRWDb())
                {
                    DateTime?maxEmailDate = db.Emails.GetAll().Max(e => e.ReceiveDate);
                    if (maxEmailDate.HasValue)
                    {
                        sentSince = maxEmailDate.Value.AddHours(-5);
                    }
                }

                uint lastUid = 0;

                //_log.Info(String.Join("; ", imap.ListMailboxes()));
                //var uids = new List<uint>(imap.Search(SearchCondition.SentSince(sentSince).Or(SearchCondition.GreaterThan(lastUid)), "INBOX"));
                var uids = new List <uint>();
                if (_settings.IsDebug)
                {
                    uids = new List <uint>()
                    {
                        30456
                    };
                    //  imap.Search(SearchCondition.Subject("kimlimu_cecku3g5 sent a message about Peppa Pig Little Girls"), folder).ToList();}
                }
                else
                {
                    SearchCondition toCriteria = null;
                    if (acceptingToAddresses != null && acceptingToAddresses.Any())
                    {
                        foreach (var to in acceptingToAddresses)
                        {
                            toCriteria = toCriteria == null?SearchCondition.To(to) : toCriteria.Or(SearchCondition.To(to));
                        }
                    }

                    SearchCondition fromCriteria = null;
                    if (acceptingFromAddresses != null && acceptingFromAddresses.Any())
                    {
                        foreach (var from in acceptingFromAddresses)
                        {
                            fromCriteria = fromCriteria == null?SearchCondition.From(from) : fromCriteria.Or(SearchCondition.From(from));
                        }
                    }

                    var searchCriteria = SearchCondition.SentSince(sentSince);
                    if (toCriteria != null)
                    {
                        searchCriteria = searchCriteria.And(toCriteria);
                    }
                    if (fromCriteria != null)
                    {
                        searchCriteria = searchCriteria.And(fromCriteria);
                    }
                    uids = new List <uint>(imap.Search(searchCriteria, folder));
                }


                foreach (var uid in uids)
                {
                    if (cancel.HasValue && cancel.Value.IsCancellationRequested)
                    {
                        _log.Info("Cancellation Requested!");
                        cancel.Value.ThrowIfCancellationRequested();
                    }


                    _log.Info("Begin check uid: " + uid);
                    var emailProcessingThread = new Thread(() => GetEmail(_dbFactory, imap, _time.GetUtcTime(), uid, folder));
                    emailProcessingThread.Priority = ThreadPriority.Highest;
                    emailProcessingThread.Start();

                    if (_settings.IsDebug)
                    {
                        emailProcessingThread.Join();
                    }
                    else
                    {
                        if (!emailProcessingThread.Join(_settings.ProcessMessageThreadTimeout))
                        {
                            emailProcessingThread.Abort();
                            throw new Exception("Timeout exceeded while processing email. Uid:" + uid);
                        }
                    }
                }

                Console.WriteLine(uids.Count);
            }
        }
Ejemplo n.º 34
0
 public AuthorizedUser(string log, string pas, ImapClient im)
 {
     login      = log;
     passw      = pas;
     imapClient = im;
 }
        public override void RunCommand(object sender)
        {
            var engine = (AutomationEngineInstance)sender;

            string vIMAPHost                = v_IMAPHost.ConvertUserVariableToString(engine);
            string vIMAPPort                = v_IMAPPort.ConvertUserVariableToString(engine);
            string vIMAPUserName            = v_IMAPUserName.ConvertUserVariableToString(engine);
            string vIMAPPassword            = v_IMAPPassword.ConvertUserVariableToString(engine);
            string vIMAPSourceFolder        = v_IMAPSourceFolder.ConvertUserVariableToString(engine);
            string vIMAPFilter              = v_IMAPFilter.ConvertUserVariableToString(engine);
            string vIMAPMessageDirectory    = v_IMAPMessageDirectory.ConvertUserVariableToString(engine);
            string vIMAPAttachmentDirectory = v_IMAPAttachmentDirectory.ConvertUserVariableToString(engine);

            using (var client = new ImapClient())
            {
                client.ServerCertificateValidationCallback = (sndr, certificate, chain, sslPolicyErrors) => true;
                client.SslProtocols = SslProtocols.None;

                using (var cancel = new CancellationTokenSource())
                {
                    try
                    {
                        client.Connect(v_IMAPHost, int.Parse(v_IMAPPort), true, cancel.Token);                         //SSL
                    }
                    catch (Exception)
                    {
                        client.Connect(v_IMAPHost, int.Parse(v_IMAPPort));                         //TLS
                    }

                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    client.Authenticate(vIMAPUserName, vIMAPPassword, cancel.Token);

                    IMailFolder toplevel    = client.GetFolder(client.PersonalNamespaces[0]);
                    IMailFolder foundFolder = FindFolder(toplevel, vIMAPSourceFolder);

                    if (foundFolder != null)
                    {
                        foundFolder.Open(FolderAccess.ReadWrite, cancel.Token);
                    }
                    else
                    {
                        throw new Exception("Source Folder not found");
                    }

                    SearchQuery query;
                    if (vIMAPFilter.ToLower() == "none")
                    {
                        query = SearchQuery.All;
                    }
                    else if (!string.IsNullOrEmpty(vIMAPFilter.Trim()))
                    {
                        query = SearchQuery.MessageContains(vIMAPFilter)
                                .Or(SearchQuery.SubjectContains(vIMAPFilter))
                                .Or(SearchQuery.FromContains(vIMAPFilter))
                                .Or(SearchQuery.BccContains(vIMAPFilter))
                                .Or(SearchQuery.BodyContains(vIMAPFilter))
                                .Or(SearchQuery.CcContains(vIMAPFilter))
                                .Or(SearchQuery.ToContains(vIMAPFilter));
                    }
                    else
                    {
                        throw new NullReferenceException("Filter not specified");
                    }

                    if (v_IMAPGetUnreadOnly == "Yes")
                    {
                        query = query.And(SearchQuery.NotSeen);
                    }

                    var filteredItems = foundFolder.Search(query, cancel.Token);

                    List <MimeMessage> outMail = new List <MimeMessage>();

                    foreach (UniqueId uid in filteredItems)
                    {
                        if (v_IMAPMarkAsRead == "Yes")
                        {
                            foundFolder.AddFlags(uid, MessageFlags.Seen, true);
                        }

                        MimeMessage message = foundFolder.GetMessage(uid, cancel.Token);

                        if (v_IMAPSaveMessagesAndAttachments == "Yes")
                        {
                            ProcessEmail(message, vIMAPMessageDirectory, vIMAPAttachmentDirectory);
                        }

                        message.MessageId = $"{vIMAPSourceFolder}#{uid}";
                        outMail.Add(message);
                    }
                    outMail.StoreInUserVariable(engine, v_OutputUserVariableName);

                    client.Disconnect(true, cancel.Token);
                    client.ServerCertificateValidationCallback = null;
                }
            }
        }
Ejemplo n.º 36
0
        public static void Main(string[] args)
        {
            using (var client = new ImapClient())
            {
                // Basic IMAP connection
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect("imap.gmail.com", 993, true);

                client.Authenticate("*****@*****.**", "Chinook@8");

                // Access email Inbox
                var inbox = client.Inbox;
                inbox.Open(FolderAccess.ReadOnly);

                Console.WriteLine("Total messages: {0}", inbox.Count);

                // Regex to match Sales from 6000 to 7999
                Regex rgxSubject = new Regex(@"\b(6[0-9][0-9][0-9]|7[0-9][0-9][0-9])\b");

                /* Carrier BoL Regex:
                 * COSCO        => ((CCLU|CSLU|COSU|CBHU)\d{10})
                 * Evergreen    => (EGLV\d{12})
                 * OOCL         => (OOLU\d{10})
                 * Matson       => (MATS\d{10})
                 * Maersk       => (MAEU\d{9})
                 * K-Line       => (KKLUAA(A|1)\d{6})
                 * MSC          => (MSCUA(A|1)\d{6})
                 * Hapag-Lloyd  => (HLCUAA(A|1)\d{9})
                 * CMA CGM      => ((CMAU|CMDU)AAA\d{7})
                 * Hyundai      => (HMDUAAAA\d{7})|(HDMU\w{4}\d{7})|(QSWB\d{7})
                 * NYK          => (NYKSAAAA\d{8})
                 * Yang Ming    => (YMLU(E|B|T|W)\d{9})
                 * UASC Lines   => (UASUAAAAA\d{6})
                 * ZIM          => ((ZIMU|SSPH)AAA\d{4,7})
                 * MOL          => (MOLU\d{11}A)
                 * Hamburg Süd  => (SUDU\d{5}\w{7})
                 * APL          => ((APLU0|APLU)\d{8})
                 * SM Lines     => (SMLM\w{4}\d{8})
                 * Turkon Lines => (TRKU\w{6}\d{6})\b")
                 */

                // Regex to Match BoL
                Regex rgxLading = new Regex(@"\b(QSWB\d{7})|(TRKU\w{6}\d{6})|(SMLM\w{4}\d{8})|(HDMU\w{4}\d{7})|((APLU0|APLU)\d{8})|(SUDU\d{5}\w{7})|(MOLU\d{11}A)|((ZIMU|SSPH)AAA\d{4,7})|(UASUAAAAA\d{6})|(YMLU(E|B|T|W)\d{9})|(NYKSAAAA\d{8})|(HMDUAAAA\d{7})|((CMAU|CMDU)AAA\d{7})|(HLCUAA(A|1)\d{9})|(MSCUA(A|1)\d{6})|(MATS\d{10})|(MAEU\d{9})|(KKLUAA(A|1)\d{6})|(EGLV\d{12})|(OOLU\d{10})|((CCLU|CSLU|COSU|CBHU)\d{10})\b");



                //Regex to Match Container, will also check the false positive match of QSWB BoL that has the same 4 characters and seven numbers of a Container.
                Regex rgxContainer = new Regex(@"\b(?!QSWB)(\w{4}\d{7})\b");

                var sales = new SalesOrderList();



                //Fetch Subjects to save time and bandwidth, before we match the subject we don't really need the full message download.
                foreach (var summary in inbox.Fetch(0, inbox.Count, MessageSummaryItems.Full | MessageSummaryItems.UniqueId))
                {
                    //will stop if message has no subject - TO DO
                    if (rgxSubject.IsMatch(summary.Envelope.Subject))
                    {
                        var textBody = (TextPart)inbox.GetBodyPart(summary.UniqueId, summary.TextBody);

                        if (rgxLading.IsMatch(textBody.Text))
                        {
                            if (rgxContainer.IsMatch(textBody.Text))
                            {
                                string    saleNumber = rgxSubject.Match(summary.Envelope.Subject).ToString();
                                string    bol        = rgxLading.Match(textBody.Text).ToString();
                                string    container  = rgxContainer.Match(textBody.Text).ToString();
                                SaleOrder matchedSale;

                                //Download the complete message to save attachment filename.
                                MimeMessage completeMessage = inbox.GetMessage(summary.UniqueId);

                                //Unique SaleNumber Constraint check, will try to find an object with the same
                                //SaleNumber
                                if (sales.Contains(new SaleOrder(Int32.Parse(saleNumber), bol, container)))
                                {
                                    matchedSale = sales.GetById(Int32.Parse(saleNumber));
                                    matchedSale.ContainerNumber = container;
                                    matchedSale.BillLading      = bol;
                                }
                                else
                                {
                                    matchedSale = new SaleOrder(Int32.Parse(saleNumber), bol, container);
                                    sales.Add(matchedSale);
                                }
                                //if any attachament it will Iterate through and save filename in the SaleOrder Object.
                                foreach (var attachment in completeMessage.Attachments)
                                {
                                    var fileName = attachment.ContentDisposition?.FileName ?? attachment.ContentType.Name;
                                    matchedSale.Attachments.Add(fileName);
                                }

                                Console.WriteLine("Sale Order: {0} | Lading: {1} | Container: {2} ",
                                                  matchedSale.SaleNumber, matchedSale.BillLading, matchedSale.ContainerNumber);
                            }
                            else
                            {
                                Console.WriteLine("Matched Sale Order and BoL, Container not finded!");
                            }
                        }
                        else
                        {
                            Console.WriteLine("Matched Sale Order, BoL not finded!");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Not Matched!");
                    }
                }

                Console.WriteLine();
                Console.WriteLine("| STORED OBJECT LIST |");

                foreach (var sale in sales)
                {
                    Console.WriteLine("Sale Order: {0} | Lading: {1} | Container: {2} ",
                                      sale.SaleNumber, sale.BillLading, sale.ContainerNumber);
                    foreach (var file in sale.Attachments)
                    {
                        Console.WriteLine("File name {0}", file);
                    }
                }
                client.Disconnect(true);
            }
        }
Ejemplo n.º 37
0
        public void TestArgumentExceptions()
        {
            var commands = new List <ImapReplayCommand> ();

            commands.Add(new ImapReplayCommand("", "dovecot.greeting.txt"));
            commands.Add(new ImapReplayCommand("A00000000 LOGIN username password\r\n", "dovecot.authenticate+gmail-capabilities.txt"));
            commands.Add(new ImapReplayCommand("A00000001 NAMESPACE\r\n", "dovecot.namespace.txt"));
            commands.Add(new ImapReplayCommand("A00000002 LIST \"\" \"INBOX\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-inbox.txt"));
            commands.Add(new ImapReplayCommand("A00000003 LIST (SPECIAL-USE) \"\" \"*\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-special-use.txt"));
            commands.Add(new ImapReplayCommand("A00000004 SELECT INBOX (CONDSTORE)\r\n", "common.select-inbox.txt"));

            using (var client = new ImapClient()) {
                var credentials = new NetworkCredential("username", "password");

                try {
                    client.ReplayConnect("localhost", new ImapReplayStream(commands, false));
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Connect: {0}", ex);
                }

                // Note: we do not want to use SASL at all...
                client.AuthenticationMechanisms.Clear();

                try {
                    client.Authenticate(credentials);
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Authenticate: {0}", ex);
                }

                Assert.IsInstanceOf <ImapEngine> (client.Inbox.SyncRoot, "SyncRoot");

                var inbox = (ImapFolder)client.Inbox;
                inbox.Open(FolderAccess.ReadWrite);

                // AddFlags
                Assert.Throws <ArgumentException> (() => inbox.AddFlags(-1, MessageFlags.Seen, true));
                Assert.Throws <ArgumentException> (async() => await inbox.AddFlagsAsync(-1, MessageFlags.Seen, true));
                Assert.Throws <ArgumentException> (() => inbox.AddFlags(0, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (async() => await inbox.AddFlagsAsync(0, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (() => inbox.AddFlags(UniqueId.MinValue, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (async() => await inbox.AddFlagsAsync(UniqueId.MinValue, MessageFlags.None, true));
                Assert.Throws <ArgumentNullException> (() => inbox.AddFlags((IList <int>)null, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.AddFlagsAsync((IList <int>)null, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (() => inbox.AddFlags((IList <UniqueId>)null, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.AddFlagsAsync((IList <UniqueId>)null, MessageFlags.Seen, true));
                Assert.Throws <ArgumentException> (() => inbox.AddFlags(new int [] { 0 }, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (async() => await inbox.AddFlagsAsync(new int [] { 0 }, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (() => inbox.AddFlags(UniqueIdRange.All, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (async() => await inbox.AddFlagsAsync(UniqueIdRange.All, MessageFlags.None, true));
                Assert.Throws <ArgumentNullException> (() => inbox.AddFlags((IList <int>)null, 1, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.AddFlagsAsync((IList <int>)null, 1, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (() => inbox.AddFlags((IList <UniqueId>)null, 1, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.AddFlagsAsync((IList <UniqueId>)null, 1, MessageFlags.Seen, true));
                Assert.Throws <ArgumentException> (() => inbox.AddFlags(new int [] { 0 }, 1, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (async() => await inbox.AddFlagsAsync(new int [] { 0 }, 1, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (() => inbox.AddFlags(UniqueIdRange.All, 1, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (async() => await inbox.AddFlagsAsync(UniqueIdRange.All, 1, MessageFlags.None, true));

                // RemoveFlags
                Assert.Throws <ArgumentException> (() => inbox.RemoveFlags(-1, MessageFlags.Seen, true));
                Assert.Throws <ArgumentException> (async() => await inbox.RemoveFlagsAsync(-1, MessageFlags.Seen, true));
                Assert.Throws <ArgumentException> (() => inbox.RemoveFlags(0, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (async() => await inbox.RemoveFlagsAsync(0, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (() => inbox.RemoveFlags(UniqueId.MinValue, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (async() => await inbox.RemoveFlagsAsync(UniqueId.MinValue, MessageFlags.None, true));
                Assert.Throws <ArgumentNullException> (() => inbox.RemoveFlags((IList <int>)null, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.RemoveFlagsAsync((IList <int>)null, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (() => inbox.RemoveFlags((IList <UniqueId>)null, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.RemoveFlagsAsync((IList <UniqueId>)null, MessageFlags.Seen, true));
                Assert.Throws <ArgumentException> (() => inbox.RemoveFlags(new int [] { 0 }, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (async() => await inbox.RemoveFlagsAsync(new int [] { 0 }, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (() => inbox.RemoveFlags(UniqueIdRange.All, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (async() => await inbox.RemoveFlagsAsync(UniqueIdRange.All, MessageFlags.None, true));
                Assert.Throws <ArgumentNullException> (() => inbox.RemoveFlags((IList <int>)null, 1, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.RemoveFlagsAsync((IList <int>)null, 1, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (() => inbox.RemoveFlags((IList <UniqueId>)null, 1, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.RemoveFlagsAsync((IList <UniqueId>)null, 1, MessageFlags.Seen, true));
                Assert.Throws <ArgumentException> (() => inbox.RemoveFlags(new int [] { 0 }, 1, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (async() => await inbox.RemoveFlagsAsync(new int [] { 0 }, 1, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (() => inbox.RemoveFlags(UniqueIdRange.All, 1, MessageFlags.None, true));
                Assert.Throws <ArgumentException> (async() => await inbox.RemoveFlagsAsync(UniqueIdRange.All, 1, MessageFlags.None, true));

                // SetFlags
                Assert.Throws <ArgumentException> (() => inbox.SetFlags(-1, MessageFlags.Seen, true));
                Assert.Throws <ArgumentException> (async() => await inbox.SetFlagsAsync(-1, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (() => inbox.SetFlags((IList <int>)null, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.SetFlagsAsync((IList <int>)null, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (() => inbox.SetFlags((IList <UniqueId>)null, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.SetFlagsAsync((IList <UniqueId>)null, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (() => inbox.SetFlags((IList <int>)null, 1, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.SetFlagsAsync((IList <int>)null, 1, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (() => inbox.SetFlags((IList <UniqueId>)null, 1, MessageFlags.Seen, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.SetFlagsAsync((IList <UniqueId>)null, 1, MessageFlags.Seen, true));

                var labels      = new string [] { "Label1", "Label2" };
                var emptyLabels = new string[0];

                // AddLabels
                Assert.Throws <ArgumentException> (() => inbox.AddLabels(-1, labels, true));
                Assert.Throws <ArgumentException> (async() => await inbox.AddLabelsAsync(-1, labels, true));
                Assert.Throws <ArgumentNullException> (() => inbox.AddLabels(0, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.AddLabelsAsync(0, null, true));
                Assert.Throws <ArgumentNullException> (() => inbox.AddLabels(UniqueId.MinValue, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.AddLabelsAsync(UniqueId.MinValue, null, true));
                Assert.Throws <ArgumentNullException> (() => inbox.AddLabels((IList <int>)null, labels, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.AddLabelsAsync((IList <int>)null, labels, true));
                Assert.Throws <ArgumentNullException> (() => inbox.AddLabels((IList <UniqueId>)null, labels, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.AddLabelsAsync((IList <UniqueId>)null, labels, true));
                Assert.Throws <ArgumentNullException> (() => inbox.AddLabels(new int [] { 0 }, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.AddLabelsAsync(new int [] { 0 }, null, true));
                Assert.Throws <ArgumentNullException> (() => inbox.AddLabels(UniqueIdRange.All, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.AddLabelsAsync(UniqueIdRange.All, null, true));
                Assert.Throws <ArgumentException> (() => inbox.AddLabels(new int [] { 0 }, emptyLabels, true));
                Assert.Throws <ArgumentException> (async() => await inbox.AddLabelsAsync(new int [] { 0 }, emptyLabels, true));
                Assert.Throws <ArgumentException> (() => inbox.AddLabels(UniqueIdRange.All, emptyLabels, true));
                Assert.Throws <ArgumentException> (async() => await inbox.AddLabelsAsync(UniqueIdRange.All, emptyLabels, true));

                Assert.Throws <ArgumentNullException> (() => inbox.AddLabels((IList <int>)null, 1, labels, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.AddLabelsAsync((IList <int>)null, 1, labels, true));
                Assert.Throws <ArgumentNullException> (() => inbox.AddLabels((IList <UniqueId>)null, 1, labels, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.AddLabelsAsync((IList <UniqueId>)null, 1, labels, true));
                Assert.Throws <ArgumentNullException> (() => inbox.AddLabels(new int [] { 0 }, 1, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.AddLabelsAsync(new int [] { 0 }, 1, null, true));
                Assert.Throws <ArgumentNullException> (() => inbox.AddLabels(UniqueIdRange.All, 1, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.AddLabelsAsync(UniqueIdRange.All, 1, null, true));
                Assert.Throws <ArgumentException> (() => inbox.AddLabels(new int [] { 0 }, 1, emptyLabels, true));
                Assert.Throws <ArgumentException> (async() => await inbox.AddLabelsAsync(new int [] { 0 }, 1, emptyLabels, true));
                Assert.Throws <ArgumentException> (() => inbox.AddLabels(UniqueIdRange.All, 1, emptyLabels, true));
                Assert.Throws <ArgumentException> (async() => await inbox.AddLabelsAsync(UniqueIdRange.All, 1, emptyLabels, true));

                // RemoveLabels
                Assert.Throws <ArgumentException> (() => inbox.RemoveLabels(-1, labels, true));
                Assert.Throws <ArgumentException> (async() => await inbox.RemoveLabelsAsync(-1, labels, true));
                Assert.Throws <ArgumentNullException> (() => inbox.RemoveLabels(0, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.RemoveLabelsAsync(0, null, true));
                Assert.Throws <ArgumentNullException> (() => inbox.RemoveLabels(UniqueId.MinValue, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.RemoveLabelsAsync(UniqueId.MinValue, null, true));
                Assert.Throws <ArgumentNullException> (() => inbox.RemoveLabels((IList <int>)null, labels, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.RemoveLabelsAsync((IList <int>)null, labels, true));
                Assert.Throws <ArgumentNullException> (() => inbox.RemoveLabels((IList <UniqueId>)null, labels, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.RemoveLabelsAsync((IList <UniqueId>)null, labels, true));
                Assert.Throws <ArgumentNullException> (() => inbox.RemoveLabels(new int [] { 0 }, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.RemoveLabelsAsync(new int [] { 0 }, null, true));
                Assert.Throws <ArgumentNullException> (() => inbox.RemoveLabels(UniqueIdRange.All, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.RemoveLabelsAsync(UniqueIdRange.All, null, true));
                Assert.Throws <ArgumentException> (() => inbox.RemoveLabels(new int [] { 0 }, emptyLabels, true));
                Assert.Throws <ArgumentException> (async() => await inbox.RemoveLabelsAsync(new int [] { 0 }, emptyLabels, true));
                Assert.Throws <ArgumentException> (() => inbox.RemoveLabels(UniqueIdRange.All, emptyLabels, true));
                Assert.Throws <ArgumentException> (async() => await inbox.RemoveLabelsAsync(UniqueIdRange.All, emptyLabels, true));

                Assert.Throws <ArgumentNullException> (() => inbox.RemoveLabels((IList <int>)null, 1, labels, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.RemoveLabelsAsync((IList <int>)null, 1, labels, true));
                Assert.Throws <ArgumentNullException> (() => inbox.RemoveLabels((IList <UniqueId>)null, 1, labels, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.RemoveLabelsAsync((IList <UniqueId>)null, 1, labels, true));
                Assert.Throws <ArgumentNullException> (() => inbox.RemoveLabels(new int [] { 0 }, 1, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.RemoveLabelsAsync(new int [] { 0 }, 1, null, true));
                Assert.Throws <ArgumentNullException> (() => inbox.RemoveLabels(UniqueIdRange.All, 1, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.RemoveLabelsAsync(UniqueIdRange.All, 1, null, true));
                Assert.Throws <ArgumentException> (() => inbox.RemoveLabels(new int [] { 0 }, 1, emptyLabels, true));
                Assert.Throws <ArgumentException> (async() => await inbox.RemoveLabelsAsync(new int [] { 0 }, 1, emptyLabels, true));
                Assert.Throws <ArgumentException> (() => inbox.RemoveLabels(UniqueIdRange.All, 1, emptyLabels, true));
                Assert.Throws <ArgumentException> (async() => await inbox.RemoveLabelsAsync(UniqueIdRange.All, 1, emptyLabels, true));

                // SetLabels
                Assert.Throws <ArgumentException> (() => inbox.SetLabels(-1, labels, true));
                Assert.Throws <ArgumentException> (async() => await inbox.SetLabelsAsync(-1, labels, true));
                Assert.Throws <ArgumentNullException> (() => inbox.SetLabels(0, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.SetLabelsAsync(0, null, true));
                Assert.Throws <ArgumentNullException> (() => inbox.SetLabels(UniqueId.MinValue, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.SetLabelsAsync(UniqueId.MinValue, null, true));
                Assert.Throws <ArgumentNullException> (() => inbox.SetLabels((IList <int>)null, labels, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.SetLabelsAsync((IList <int>)null, labels, true));
                Assert.Throws <ArgumentNullException> (() => inbox.SetLabels((IList <UniqueId>)null, labels, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.SetLabelsAsync((IList <UniqueId>)null, labels, true));
                Assert.Throws <ArgumentNullException> (() => inbox.SetLabels(new int [] { 0 }, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.SetLabelsAsync(new int [] { 0 }, null, true));
                Assert.Throws <ArgumentNullException> (() => inbox.SetLabels(UniqueIdRange.All, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.SetLabelsAsync(UniqueIdRange.All, null, true));

                Assert.Throws <ArgumentNullException> (() => inbox.SetLabels((IList <int>)null, 1, labels, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.SetLabelsAsync((IList <int>)null, 1, labels, true));
                Assert.Throws <ArgumentNullException> (() => inbox.SetLabels((IList <UniqueId>)null, 1, labels, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.SetLabelsAsync((IList <UniqueId>)null, 1, labels, true));
                Assert.Throws <ArgumentNullException> (() => inbox.SetLabels(new int [] { 0 }, 1, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.SetLabelsAsync(new int [] { 0 }, 1, null, true));
                Assert.Throws <ArgumentNullException> (() => inbox.SetLabels(UniqueIdRange.All, 1, null, true));
                Assert.Throws <ArgumentNullException> (async() => await inbox.SetLabelsAsync(UniqueIdRange.All, 1, null, true));

                client.Disconnect(false);
            }
        }
        /// 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) { }
        }
Ejemplo n.º 39
0
        public void KonekcijaNaSmtp(string username, string password, string mailTo, string subject, string bodyText, string attachmentPath, string mailHost)
        {
            // Za proveru jel uspesno poslat mail
            bool uspesnoSlanje = true;

            // Generisemo poruku
            var msg = CreateMessage(username, mailTo, subject, bodyText, attachmentPath);

            try
            {
                // SmtpClient je od MailKit bibljioteke
                using (var clientSmtp = new SmtpClient())
                {
                    // Na koji se host konektuje (mail.bankom.rs), port, auto bira da li ima security
                    clientSmtp.Connect(mailHost, 587, SecureSocketOptions.Auto);

                    // Logovanje naseg clienta
                    clientSmtp.Authenticate(username, password);

                    // Slanje poruke
                    clientSmtp.Send(msg);

                    // Zatvaranje konekcije
                    clientSmtp.Disconnect(true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

                MessageBox.Show("Slanje nije uspelo! Greska: " + ex.Message);

                // Ukoliko izadje neka greska i client ne uspe da posalje mail, provera postaje false
                uspesnoSlanje = false;
            }

            // Ukoliko je provera true, Imap ce uploadovati poruku u sent folder
            if (uspesnoSlanje)
            {
                try
                {
                    // ImapClient je od MailKit bibljioteke
                    using (var clientImap = new ImapClient())
                    {
                        // Na koji se host konektuje (mail.bankom.rs), port, auto bira da li ima security
                        clientImap.Connect(mailHost, 993, SecureSocketOptions.Auto);

                        // Logovanje naseg clienta
                        clientImap.Authenticate(username, password);

                        // Cesta imena foldera gde se nalaze poslati mailovi
                        string[] CommonSentFolderNames = { "Sent", "Sent Items", "Sent Mail", "Sent Messages", /* maybe add some translated names */ };

                        // Da bi mogli da posaljemo kopiju maila u Sent folder moramo prvo da utvrdimo kako se Sent folder pravilno zove i zatim posaljemo mail
                        clientImap.GetFolder(clientImap.PersonalNamespaces[0]).GetSubfolders(false).FirstOrDefault(x => CommonSentFolderNames.Contains(x.Name)).Append(msg);

                        // Zatvaranje konekcije
                        clientImap.Disconnect(true);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                MessageBox.Show("Mail je uspesno poslat !");
            }
        }
Ejemplo n.º 40
0
        public static void Main(string[] args)
        {
            using (var client = new ImapClient(new ProtocolLogger(Console.OpenStandardError()))) {
                client.Connect("imap.gmail.com", 993, true);

                // Remove the XOAUTH2 authentication mechanism since we don't have an OAuth2 token.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                client.Authenticate("*****@*****.**", "password");

                client.Inbox.Open(FolderAccess.ReadOnly);

                // Get the summary information of all of the messages (suitable for displaying in a message list).
                var messages = client.Inbox.Fetch(0, -1, MessageSummaryItems.Full | MessageSummaryItems.UniqueId).ToList();

                // Keep track of messages being expunged so that when the CountChanged event fires, we can tell if it's
                // because new messages have arrived vs messages being removed (or some combination of the two).
                client.Inbox.MessageExpunged += (sender, e) => {
                    var folder = (ImapFolder)sender;

                    if (e.Index < messages.Count)
                    {
                        var message = messages[e.Index];

                        Console.WriteLine("{0}: expunged message {1}: Subject: {2}", folder, e.Index, message.Envelope.Subject);

                        // Note: If you are keeping a local cache of message information
                        // (e.g. MessageSummary data) for the folder, then you'll need
                        // to remove the message at e.Index.
                        messages.RemoveAt(e.Index);
                    }
                    else
                    {
                        Console.WriteLine("{0}: expunged message {1}: Unknown message.", folder, e.Index);
                    }
                };

                // Keep track of changes to the number of messages in the folder (this is how we'll tell if new messages have arrived).
                client.Inbox.CountChanged += (sender, e) => {
                    // Note: the CountChanged event will fire when new messages arrive in the folder and/or when messages are expunged.
                    var folder = (ImapFolder)sender;

                    Console.WriteLine("The number of messages in {0} has changed.", folder);

                    // Note: because we are keeping track of the MessageExpunged event and updating our
                    // 'messages' list, we know that if we get a CountChanged event and folder.Count is
                    // larger than messages.Count, then it means that new messages have arrived.
                    if (folder.Count > messages.Count)
                    {
                        Console.WriteLine("{0} new messages have arrived.", folder.Count - messages.Count);

                        // Note: your first instict may be to fetch these new messages now, but you cannot do
                        // that in an event handler (the ImapFolder is not re-entrant).
                        //
                        // If this code had access to the 'done' CancellationTokenSource (see below), it could
                        // cancel that to cause the IDLE loop to end.
                    }
                };

                // Keep track of flag changes.
                client.Inbox.MessageFlagsChanged += (sender, e) => {
                    var folder = (ImapFolder)sender;

                    Console.WriteLine("{0}: flags for message {1} have changed to: {2}.", folder, e.Index, e.Flags);
                };

                Console.WriteLine("Hit any key to end the IDLE loop.");
                using (var done = new CancellationTokenSource()) {
                    // Note: when the 'done' CancellationTokenSource is cancelled, it ends to IDLE loop.
                    var thread = new Thread(IdleLoop);

                    thread.Start(new IdleState(client, done.Token));

                    Console.ReadKey();
                    done.Cancel();
                    thread.Join();
                }

                if (client.Inbox.Count > messages.Count)
                {
                    Console.WriteLine("The new messages that arrived during IDLE are:");
                    foreach (var message in client.Inbox.Fetch(messages.Count, -1, MessageSummaryItems.Full | MessageSummaryItems.UniqueId))
                    {
                        Console.WriteLine("Subject: {0}", message.Envelope.Subject);
                    }
                }

                client.Disconnect(true);
            }
        }
Ejemplo n.º 41
0
        public void connect()
        {
            using (ImapClient client = new ImapClient())
            //  using (PopClient pop = new PopClient("pop.gmail.com"))
            {
                int pops = 1;
                // Connect and login.
                client.Connect("imap.gmail.com", 993, true);
                Console.WriteLine("Connected.");

                client.Authenticate(name, pass);
                Console.WriteLine("Authenticated.");

                var inbox = client.Inbox;
                inbox.Open(MailKit.FolderAccess.ReadOnly);
                int count = inbox.Count;

                // Check if there are any messages available on the server.
                if (inbox.Count == 0)
                {
                    return;
                }

                var query = SearchQuery.DeliveredAfter(DateTime.Parse("2020-03-11")).And(SearchQuery.BodyContains("is inviting you to a scheduled Zoom meeting."));

                foreach (var uid in inbox.Search(query))
                {
                    // Download message.
                    MimeMessage message = inbox.GetMessage(uid);

                    // Display message sender and subject.
                    //Console.WriteLine();
                    //Console.WriteLine($"From: {message.From}");
                    //Console.WriteLine($"Subject: {message.Subject}");
                    emails.Append($"From: {message.From}");
                    emails.Append($"Subject: {message.Subject}");

                    // Display message body.
                    // Console.WriteLine("Body:");
                    string body = string.IsNullOrEmpty(message.HtmlBody) ?
                                  message.TextBody :
                                  message.HtmlBody;


                    MatchCollection matches   = ZoomId.Matches(body);
                    MatchCollection joinlinks = ZoomJoinUrl.Matches(body);
                    long            lid       = 0;
                    string          link      = "";
                    if (matches.Count == 0 || joinlinks.Count == 0)
                    {
                        pops++;
                        continue;
                    }
                    if (matches.Count > 0)
                    {
                        Match  match = ZoomId.Matches(body)[0];
                        string id    = match.Value;
                        id  = id.Replace(" ", "");
                        lid = long.Parse(id);
                    }
                    if (joinlinks.Count > 0)
                    {
                        Match linksys = ZoomJoinUrl.Matches(body)[0];
                        link = linksys.Value;
                    }

                    MatchCollection times = ZoomTime.Matches(body);
                    DateTime        time  = new DateTime();
                    if (times.Count > 0)
                    {
                        Match match = ZoomTime.Matches(body)[0];
                        time = DateTime.ParseExact(match.Groups[1].Value, "MMM d, yyyy hh:mm tt", CultureInfo.InvariantCulture);
                    }

                    var meeting = new Meeting()
                    {
                        Id        = lid,
                        JoinUrl   = link,
                        StartTime = time,
                    };

                    Console.WriteLine(lid);

                    meetings.Add(meeting);
                    emails.Append(body);
                }
            }
        }
 public ImapTransactionParser(ImapClient imap)   // testable if ImapClient replaced by IMailFolder
     : this(imap, null)
 {
 }
Ejemplo n.º 43
0
        public void TestNotSupportedExceptions()
        {
            var commands = new List <ImapReplayCommand> ();

            commands.Add(new ImapReplayCommand("", "dovecot.greeting.txt"));
            commands.Add(new ImapReplayCommand("A00000000 LOGIN username password\r\n", "dovecot.authenticate+gmail-capabilities.txt"));
            commands.Add(new ImapReplayCommand("A00000001 NAMESPACE\r\n", "dovecot.namespace.txt"));
            commands.Add(new ImapReplayCommand("A00000002 LIST \"\" \"INBOX\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-inbox.txt"));
            commands.Add(new ImapReplayCommand("A00000003 LIST (SPECIAL-USE) \"\" \"*\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-special-use.txt"));
            commands.Add(new ImapReplayCommand("A00000004 SELECT INBOX\r\n", "common.select-inbox-no-modseq.txt"));

            using (var client = new ImapClient()) {
                var credentials = new NetworkCredential("username", "password");

                try {
                    client.ReplayConnect("localhost", new ImapReplayStream(commands, false));
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Connect: {0}", ex);
                }

                // Note: we do not want to use SASL at all...
                client.AuthenticationMechanisms.Clear();

                try {
                    client.Authenticate(credentials);
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Authenticate: {0}", ex);
                }

                Assert.IsInstanceOf <ImapEngine> (client.Inbox.SyncRoot, "SyncRoot");

                // disable all features
                client.Capabilities = ImapCapabilities.None;

                var inbox = (ImapFolder)client.Inbox;
                inbox.Open(FolderAccess.ReadWrite);

                var   indexes = new int[] { 0 };
                ulong modseq  = 409601020304;

                // AddFlags
                Assert.Throws <NotSupportedException> (() => inbox.AddFlags(indexes, modseq, MessageFlags.Seen, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.AddFlagsAsync(indexes, modseq, MessageFlags.Seen, true));
                Assert.Throws <NotSupportedException> (() => inbox.AddFlags(UniqueIdRange.All, modseq, MessageFlags.Seen, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.AddFlagsAsync(UniqueIdRange.All, modseq, MessageFlags.Seen, true));

                // RemoveFlags
                Assert.Throws <NotSupportedException> (() => inbox.RemoveFlags(indexes, modseq, MessageFlags.Seen, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.RemoveFlagsAsync(indexes, modseq, MessageFlags.Seen, true));
                Assert.Throws <NotSupportedException> (() => inbox.RemoveFlags(UniqueIdRange.All, modseq, MessageFlags.Seen, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.RemoveFlagsAsync(UniqueIdRange.All, modseq, MessageFlags.Seen, true));

                // SetFlags
                Assert.Throws <NotSupportedException> (() => inbox.SetFlags(indexes, modseq, MessageFlags.Seen, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.SetFlagsAsync(indexes, modseq, MessageFlags.Seen, true));
                Assert.Throws <NotSupportedException> (() => inbox.SetFlags(UniqueIdRange.All, modseq, MessageFlags.Seen, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.SetFlagsAsync(UniqueIdRange.All, modseq, MessageFlags.Seen, true));

                var labels = new string[] { "Label1", "Label2" };

                // AddLabels
                Assert.Throws <NotSupportedException> (() => inbox.AddLabels(indexes, labels, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.AddLabelsAsync(indexes, labels, true));
                Assert.Throws <NotSupportedException> (() => inbox.AddLabels(UniqueIdRange.All, labels, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.AddLabelsAsync(UniqueIdRange.All, labels, true));

                Assert.Throws <NotSupportedException> (() => inbox.AddLabels(indexes, modseq, labels, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.AddLabelsAsync(indexes, modseq, labels, true));
                Assert.Throws <NotSupportedException> (() => inbox.AddLabels(UniqueIdRange.All, modseq, labels, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.AddLabelsAsync(UniqueIdRange.All, modseq, labels, true));

                // RemoveLabels
                Assert.Throws <NotSupportedException> (() => inbox.RemoveLabels(indexes, labels, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.RemoveLabelsAsync(indexes, labels, true));
                Assert.Throws <NotSupportedException> (() => inbox.RemoveLabels(UniqueIdRange.All, labels, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.RemoveLabelsAsync(UniqueIdRange.All, labels, true));

                Assert.Throws <NotSupportedException> (() => inbox.RemoveLabels(indexes, modseq, labels, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.RemoveLabelsAsync(indexes, modseq, labels, true));
                Assert.Throws <NotSupportedException> (() => inbox.RemoveLabels(UniqueIdRange.All, modseq, labels, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.RemoveLabelsAsync(UniqueIdRange.All, modseq, labels, true));

                // SetLabels
                Assert.Throws <NotSupportedException> (() => inbox.SetLabels(indexes, labels, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.SetLabelsAsync(indexes, labels, true));
                Assert.Throws <NotSupportedException> (() => inbox.SetLabels(UniqueIdRange.All, labels, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.SetLabelsAsync(UniqueIdRange.All, labels, true));

                Assert.Throws <NotSupportedException> (() => inbox.SetLabels(indexes, modseq, labels, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.SetLabelsAsync(indexes, modseq, labels, true));
                Assert.Throws <NotSupportedException> (() => inbox.SetLabels(UniqueIdRange.All, modseq, labels, true));
                Assert.Throws <NotSupportedException> (async() => await inbox.SetLabelsAsync(UniqueIdRange.All, modseq, labels, true));

                client.Disconnect(false);
            }
        }
Ejemplo n.º 44
0
        public EmailData TestEmails(EmailData data)
        {
            var client = new ImapClient(data.ImapServer, data.Port, data.Ssl);

            try
            {
                client.Connect();
                client.Login(data.Login, data.Password);
                var dt = new EmailHelpers().DateForEmailFiler(data.InquireDate);
                _messageList = client.Folders.Inbox.Search($"SINCE {dt}").Where(message => message.Attachments.Any(attachment => _searchFileExt.IsMatch(attachment.FileName))).ToList();

                if (_messageList != null && _messageList.Any())
                {
                    foreach (var message in _messageList)
                    {
                        if (_receivedMessagesUids.Contains(message.UId.ToString()))
                        {
                            continue;
                        }
                        foreach (var attachment in message.Attachments)
                        {
                            if (!attachment.Downloaded)
                            {
                                attachment.Download();
                            }
                            var dir = $"{SavePath}{data.Email}\\{DateTime.Today.ToLongDateString()}";
                            var mes = SaveAttachmentToDisk(attachment, dir);
                            SaveResultToDatabase(new EmailMessage
                            {
                                Parsed   = false,
                                Subject  = message.Subject,
                                Received = DateTime.Now,
                                Uid      = message.UId.ToString(),
                                ReceipientMailAddress = data.Email,
                                FileAttachName        = mes,
                                From = message.From.Address
                            });
                        }
                    }
                    data.Result = new EmailLoadResult()
                    {
                        Result =
                            $"{data.Email} is successful authenticated at {DateTime.Now.ToLongDateString()}, mess: {string.Join(" / ", _messageList.Select(message => message.Subject))} with agent: {AgentGuid}",
                        Success = true
                    };
                }
                else
                {
                    data.Result = new EmailLoadResult()
                    {
                        Result =
                            $"{data.Email} is successful authenticated at {DateTime.Now.ToLongDateString()}, but no files recieved with agent: {AgentGuid}",
                        Success = true
                    };
                }
            }
            catch (Exception e)
            {
                data.Result = new EmailLoadResult()
                {
                    Result  = $"{data.Email} throw exception:\"{e.Message}\" at {DateTime.Now.ToLongDateString()} with agent: {AgentGuid}",
                    Success = false
                };
            }
            //client.Logout();
            return(data);
        }
Ejemplo n.º 45
0
 private void InitImapClient()
 {
     imapClient = new ImapClient("imap.gmail.com", 993,
                                 user.username, user.password, AuthMethod.Login, true);
 }
        private DashBoardMailBoxJob ReceiveMails()
        {
            DashBoardMailBoxJob model = new DashBoardMailBoxJob();

            model.Inbox = new List <MailMessege>();

            try
            {
                EmailConfiguration email = new EmailConfiguration();
                email.POPServer    = "imap.gmail.com"; // type your popserver
                email.POPUsername  = "";               // type your username credential
                email.POPpassword  = "";               // type your password credential
                email.IncomingPort = "993";
                email.IsPOPssl     = true;


                int        success = 0;
                int        fail    = 0;
                ImapClient ic      = new ImapClient(email.POPServer, email.POPUsername, email.POPpassword, AuthMethods.Login, Convert.ToInt32(email.IncomingPort), (bool)email.IsPOPssl);
                // Select a mailbox. Case-insensitive
                ic.SelectMailbox("INBOX");
                int i        = 1;
                int msgcount = ic.GetMessageCount("INBOX");
                int end      = msgcount - 1;
                int start    = msgcount - 40;
                // Note that you must specify that headersonly = false
                // when using GetMesssages().
                MailMessage[] mm = ic.GetMessages(start, end, false);
                foreach (var item in mm)
                {
                    MailMessege obj = new MailMessege();
                    try
                    {
                        obj.UID      = item.Uid;
                        obj.subject  = item.Subject;
                        obj.sender   = item.From.ToString();
                        obj.sendDate = item.Date;
                        if (item.Attachments == null)
                        {
                        }
                        else
                        {
                            obj.Attachments = item.Attachments;
                        }

                        model.Inbox.Add(obj);
                        success++;
                    }
                    catch (Exception e)
                    {
                        DefaultLogger.Log.LogError(
                            "TestForm: Message fetching failed: " + e.Message + "\r\n" +
                            "Stack trace:\r\n" +
                            e.StackTrace);
                        fail++;
                    }
                    i++;
                }
                ic.Dispose();
                model.Inbox = model.Inbox.OrderByDescending(m => m.sendDate).ToList();
                model.mess  = "Mail received!\nSuccesses: " + success + "\nFailed: " + fail + "\nMessage fetching done";

                if (fail > 0)
                {
                    model.mess = "Since some of the emails were not parsed correctly (exceptions were thrown)\r\n" +
                                 "please consider sending your log file to the developer for fixing.\r\n" +
                                 "If you are able to include any extra information, please do so.";
                }
            }

            catch (Exception e)
            {
                model.mess = "Error occurred retrieving mail. " + e.Message;
            }
            finally
            {
            }
            return(model);
        }
Ejemplo n.º 47
0
        public async Task <string> GetVerificationCode()
        {
            int started = Environment.TickCount;

            // email should not be older than 1 minute
            DateTime border = DateTime.Now.Subtract(TimeSpan.FromMinutes(1));

            await Task.Delay(initialWaitTime);

            string vcode = null;

            try
            {
                ImapClient client = new ImapClient();
                await client.ConnectAsync(Config.Host, Config.Port, MailKit.Security.SecureSocketOptions.Auto);

                await client.AuthenticateAsync(Config.Username, Config.Password);

                var inbox = await client.GetFolderAsync(Config.ImapFolderPath);

                List <MimeMessage>  msgList = null;
                MimeKit.MimeMessage mail    = null;

                while (mail == null)
                {
                    await inbox.OpenAsync(FolderAccess.ReadWrite);

                    // we need a list to determine the message's index reliably
                    msgList = inbox.ToList();
                    mail    = msgList.FirstOrDefault(x => x.From.Mailboxes.Any(f => f.Address.ToLower().Contains(Config.VerificationFromAddress.ToLower())) && x.Subject.Contains(Config.VerificationMailSubject) && x.Date >= border);
                    if (mail != null)
                    {
                        break;
                    }

                    // wait then retry
                    await inbox.CloseAsync();

                    if (Environment.TickCount - started > timeout.TotalMilliseconds)
                    {
                        throw new TimeoutException();
                    }
                    await Task.Delay(retryWaitTime);
                }

                string msg_content = mail.TextBody;
                vcode = ExtractVerificationCode(msg_content);

                // since we are going to use the VerificationCode, delete the message
                if (msgList != null)
                {
                    int midx = msgList.IndexOf(mail);
                    inbox.AddFlags(midx, MessageFlags.Deleted, true);
                    await inbox.ExpungeAsync();
                }

                await inbox.CloseAsync();

                await client.DisconnectAsync(true);
            }
            catch (Exception e)
            {
                // maybe we still got the verification code
            }

            // return what we have
            return(vcode);
        }
Ejemplo n.º 48
0
        public static void getEmail()
        {
            if (accForm.tmpUsername == "Guest" || accForm.tmpUsername == "")
            {
                return;
            }

            using (var client = new ImapClient())
            {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                try
                {
                    client.Connect(host, imapPort, true);
                }
                catch
                {
                    MessageBox.Show("Connection to email server failed!");
                    return;
                }

                try
                {
                    client.Authenticate(accForm.tmpUsername + "@aolemu.com", accForm.tmpPassword);
                }
                catch
                {
                    MessageBox.Show("Authentication Failed!");
                    return;
                }

                var inbox = client.Inbox;
                inbox.Open(FolderAccess.ReadOnly);

                // new emails
                var uids  = inbox.Search(SearchQuery.NotSeen);
                var items = inbox.Fetch(uids, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure | MessageSummaryItems.Envelope | MessageSummaryItems.Flags);
                foreach (var i in items)
                {
                    if (i.Flags == MessageFlags.Deleted)
                    {
                        continue;
                    }
                    var message = inbox.GetMessage(i.UniqueId);
                    //Debug.WriteLine("[MAIL] new id:" + message.MessageId + " subj:" + message.Subject);
                    if (!emailsNew.ContainsKey(message.MessageId))
                    {
                        emailsNew.Add(message.MessageId, message.Subject);
                    }
                }

                // old emails
                uids  = inbox.Search(SearchQuery.Seen);
                items = inbox.Fetch(uids, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure | MessageSummaryItems.Envelope | MessageSummaryItems.Flags);
                foreach (var i in items)
                {
                    var message = inbox.GetMessage(i.UniqueId);
                    //Debug.WriteLine("[MAIL] old id:" + message.MessageId + " subj:" + message.Subject);
                    if (message.MessageId == null)
                    {
                        break;
                    }
                    if (!emailsOld.ContainsKey(message.MessageId))
                    {
                        emailsOld.Add(message.MessageId, message.Subject);
                    }
                }

                var outbox = client.GetFolder(SpecialFolder.Sent);
                outbox.Open(FolderAccess.ReadOnly);
                Debug.WriteLine("outbox items: " + outbox.Count);

                // sent emails
                for (int i = 0; i < outbox.Count; i++)
                {
                    var message = outbox.GetMessage(i);
                    //Debug.WriteLine("[MAIL] sent id:" + message.MessageId + " subj:" + message.Subject);
                    if (!emailsSent.ContainsKey(message.MessageId))
                    {
                        emailsSent.Add(message.MessageId, message.Subject);
                    }
                }

                client.Disconnect(true);
            }
        }
Ejemplo n.º 49
0
		private static void Initialize()
		{
			using (var client = new ImapClient())
			{
				client.Connect("imap.gmail.com", 993, true);

				client.AuthenticationMechanisms.Remove("XOAUTH");

				client.Authenticate("breshch", "Mp~7200~aA");

				var query = SearchQuery.DeliveredAfter(DateTime.Now.AddDays(-1)).And(SearchQuery.All);

				var cardsFolder = client.GetFolder("Cards");
				cardsFolder.Open(FolderAccess.ReadOnly);


				foreach (var uid in cardsFolder.Search(query))
				{
					var message = cardsFolder.GetMessage(uid);
					var textPart = message.BodyParts.First() as TextPart;

					var date = message.Date.LocalDateTime;
					var body = textPart.GetText(Encoding.UTF8);

					using (var bc = new BusinessContext())
					{
						if (!bc.IsNewMessage(date, body))
						{
							continue;
						}
					}

					var subject = message.Subject;

					string bankName = subject.Substring(subject.LastIndexOf(" ")).Trim();
					
					CardBase card = null;

					switch (bankName)
					{
						case "VTB24":
							card = new CardVTB24(body);
							break;
						case "PSB":
							card = new CardPSB(body);
							break;
					}

					double? sum = card.GetSum();

					if (sum != null)
					{
						using (var bc = new BusinessContext())
						{
							bc.AddInfoSafeCard(date, sum.Value, Currency.RUR, body, bankName);
						}
					}

					using (var sw = new StreamWriter("mails.txt", true))
					{
						sw.WriteLine(DateTime.Now + "\t" + date + "\t" + sum + "\t" + body);
					}
				}

				client.Disconnect(true);
			}
		}
Ejemplo n.º 50
0
 public BodyStructureParser(string data, ImapClient client, Message message)
 {
     _reader  = new StringReader(data);
     _client  = client;
     _message = message;
 }
        private void GetEmail(IDbFactory dbFactory, ImapClient imap, DateTime scanDate, uint uid, string folder)
        {
            _threadExceptions.Clear();

            using (var db = dbFactory.GetRWDb())
            {
                //TODO: checking by UID only if UIDValidity the same after select folder
                var folderType = EmailHelper.GetFolderType(folder);
                var existEmail = db.Emails.GetByUid(uid, folderType);

                if (existEmail == null)
                {
                    _log.Info("Start email processing, uid: " + uid + ", folder=" + folder);
                    try
                    {
                        EmailReadingResult readingResult = null;

                        _log.Info("Start GetMessageHeaders()");
                        var messageHeaders = imap.GetMessage(uid, FetchOptions.HeadersOnly, false, folder);
                        _log.Info("Eng GetMessageHeaders()");

                        //TODO: Now not working (no logic to read labels from headers)
                        var labels = EmailParserHelper.GetMessageLabels(messageHeaders.Headers);
                        _log.Info("Labels: " + labels);

                        var messageID    = EmailParserHelper.GetMessageID(messageHeaders.Headers);
                        var existPOEmail = db.Emails.GetByMessageID(messageID);
                        if (existPOEmail != null)
                        {
                            db.Emails.UpdateUID(existPOEmail.Id, uid);
                            _log.Info("UID updated:" + uid + "for exist email, subject: " + existPOEmail.Subject);

                            readingResult = new EmailReadingResult()
                            {
                                Email   = existPOEmail,
                                Headers = messageHeaders.Headers,
                                Folder  = folder,
                                Status  = EmailMatchingResultStatus.Existing
                            };
                        }
                        else
                        {
                            _log.Info("Start GetMessage()");
                            var message = imap.GetMessage(uid, FetchOptions.Normal, false, folder);
                            _log.Info("Eng GetMessage(). Subject: " + message.Subject + Environment.NewLine);

                            readingResult = SaveEmail(db, message, uid, folder, scanDate);
                        }

                        _emailProcessResultList.Add(readingResult);

                        switch (readingResult.Status)
                        {
                        case EmailMatchingResultStatus.New:
                            newUidList.Add(new EmailDTO()
                            {
                                Id  = readingResult.Email.Id,
                                UID = readingResult.Email.UID
                            });
                            break;

                        case EmailMatchingResultStatus.Existing:
                            existingUidList.Add(new EmailDTO()
                            {
                                Id  = readingResult.Email.Id,
                                UID = readingResult.Email.UID
                            });
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        _log.Fatal(string.Format("Not processed Uid: {0}", uid), ex);
                        _threadExceptions.Add(new Exception(string.Format("Not processed Uid: {0}", uid), ex));
                    }

                    _log.Info("End email processing. Uid: " + uid);
                }
                else
                {
                    existingUidList.Add(new EmailDTO()
                    {
                        Id  = existEmail.Id,
                        UID = uid
                    });
                }
            }
        }
Ejemplo n.º 52
0
        public void TestExtractingPrecisePangolinAttachment()
        {
            var commands = new List <ImapReplayCommand> ();

            commands.Add(new ImapReplayCommand("", "gmail.greeting.txt"));
            commands.Add(new ImapReplayCommand("A00000000 CAPABILITY\r\n", "gmail.capability.txt"));
            commands.Add(new ImapReplayCommand("A00000001 AUTHENTICATE PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "gmail.authenticate.txt"));
            commands.Add(new ImapReplayCommand("A00000002 NAMESPACE\r\n", "gmail.namespace.txt"));
            commands.Add(new ImapReplayCommand("A00000003 LIST \"\" \"INBOX\"\r\n", "gmail.list-inbox.txt"));
            commands.Add(new ImapReplayCommand("A00000004 XLIST \"\" \"*\"\r\n", "gmail.xlist.txt"));
            commands.Add(new ImapReplayCommand("A00000005 LIST \"\" \"%\"\r\n", "gmail.list-personal.txt"));
            commands.Add(new ImapReplayCommand("A00000006 EXAMINE INBOX (CONDSTORE)\r\n", "gmail.examine-inbox.txt"));
            commands.Add(new ImapReplayCommand("A00000007 FETCH 270 (BODY.PEEK[])\r\n", "gmail.precise-pangolin-message.txt"));

            using (var client = new ImapClient()) {
                try {
                    client.ReplayConnect("localhost", new ImapReplayStream(commands, false), CancellationToken.None);
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Connect: {0}", ex);
                }

                Assert.IsTrue(client.IsConnected, "Client failed to connect.");

                Assert.AreEqual(GMailInitialCapabilities, client.Capabilities);
                Assert.AreEqual(4, client.AuthenticationMechanisms.Count);
                Assert.IsTrue(client.AuthenticationMechanisms.Contains("XOAUTH"), "Expected SASL XOAUTH auth mechanism");
                Assert.IsTrue(client.AuthenticationMechanisms.Contains("XOAUTH2"), "Expected SASL XOAUTH2 auth mechanism");
                Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism");
                Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN-CLIENTTOKEN"), "Expected SASL PLAIN-CLIENTTOKEN auth mechanism");

                try {
                    var credentials = new NetworkCredential("username", "password");

                    // Note: Do not try XOAUTH2
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    client.Authenticate(credentials, CancellationToken.None);
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Authenticate: {0}", ex);
                }

                Assert.AreEqual(GMailAuthenticatedCapabilities, client.Capabilities);

                var inbox = client.Inbox;
                Assert.IsNotNull(inbox, "Expected non-null Inbox folder.");
                Assert.AreEqual(FolderAttributes.HasNoChildren, inbox.Attributes, "Expected Inbox attributes to be \\HasNoChildren.");

                foreach (var special in Enum.GetValues(typeof(SpecialFolder)).OfType <SpecialFolder> ())
                {
                    var folder = client.GetFolder(special);

                    if (special != SpecialFolder.Archive)
                    {
                        var expected = GetSpecialFolderAttribute(special) | FolderAttributes.HasNoChildren;

                        Assert.IsNotNull(folder, "Expected non-null {0} folder.", special);
                        Assert.AreEqual(expected, folder.Attributes, "Expected {0} attributes to be \\HasNoChildren.", special);
                    }
                    else
                    {
                        Assert.IsNull(folder, "Expected null {0} folder.", special);
                    }
                }

                var personal = client.GetFolder(client.PersonalNamespaces[0]);
                var folders  = personal.GetSubfolders(false, CancellationToken.None).ToList();
                Assert.AreEqual(client.Inbox, folders[0], "Expected the first folder to be the Inbox.");
                Assert.AreEqual("[Gmail]", folders[1].FullName, "Expected the second folder to be [Gmail].");
                Assert.AreEqual(FolderAttributes.NoSelect | FolderAttributes.HasChildren, folders[1].Attributes, "Expected [Gmail] folder to be \\Noselect \\HasChildren.");

                client.Inbox.Open(FolderAccess.ReadOnly, CancellationToken.None);

                var message = client.Inbox.GetMessage(269, CancellationToken.None);

                foreach (var attachment in message.Attachments)
                {
                    using (var stream = File.Create("attachment.txt")) {
                        var options = FormatOptions.Default.Clone();
                        options.NewLineFormat = NewLineFormat.Dos;
                        attachment.WriteTo(options, stream);
                    }
                    using (var stream = File.Create(attachment.FileName)) {
                        attachment.ContentObject.DecodeTo(stream);
                        stream.Close();
                    }
                }

                client.Disconnect(false, CancellationToken.None);
            }
        }
Ejemplo n.º 53
0
        public void TestChangingFlagsOnEmptyListOfMessages()
        {
            var commands = new List <ImapReplayCommand> ();

            commands.Add(new ImapReplayCommand("", "dovecot.greeting.txt"));
            commands.Add(new ImapReplayCommand("A00000000 LOGIN username password\r\n", "dovecot.authenticate+gmail-capabilities.txt"));
            commands.Add(new ImapReplayCommand("A00000001 NAMESPACE\r\n", "dovecot.namespace.txt"));
            commands.Add(new ImapReplayCommand("A00000002 LIST \"\" \"INBOX\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-inbox.txt"));
            commands.Add(new ImapReplayCommand("A00000003 LIST (SPECIAL-USE) \"\" \"*\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-special-use.txt"));
            commands.Add(new ImapReplayCommand("A00000004 SELECT INBOX (CONDSTORE)\r\n", "common.select-inbox.txt"));

            using (var client = new ImapClient()) {
                var credentials = new NetworkCredential("username", "password");

                try {
                    client.ReplayConnect("localhost", new ImapReplayStream(commands, false));
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Connect: {0}", ex);
                }

                // Note: we do not want to use SASL at all...
                client.AuthenticationMechanisms.Clear();

                try {
                    client.Authenticate(credentials);
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Authenticate: {0}", ex);
                }

                Assert.IsInstanceOf <ImapEngine> (client.Inbox.SyncRoot, "SyncRoot");

                var inbox = (ImapFolder)client.Inbox;
                inbox.Open(FolderAccess.ReadWrite);

                ulong            modseq  = 409601020304;
                var              uids    = new UniqueId[0];
                var              indexes = new int[0];
                IList <UniqueId> unmodifiedUids;
                IList <int>      unmodifiedIndexes;

                // AddFlags
                unmodifiedIndexes = inbox.AddFlags(indexes, modseq, MessageFlags.Seen, true);
                Assert.AreEqual(0, unmodifiedIndexes.Count);

                unmodifiedUids = inbox.AddFlags(uids, modseq, MessageFlags.Seen, true);
                Assert.AreEqual(0, unmodifiedUids.Count);

                // RemoveFlags
                unmodifiedIndexes = inbox.RemoveFlags(indexes, modseq, MessageFlags.Seen, true);
                Assert.AreEqual(0, unmodifiedIndexes.Count);

                unmodifiedUids = inbox.RemoveFlags(uids, modseq, MessageFlags.Seen, true);
                Assert.AreEqual(0, unmodifiedUids.Count);

                // SetFlags
                unmodifiedIndexes = inbox.SetFlags(indexes, modseq, MessageFlags.Seen, true);
                Assert.AreEqual(0, unmodifiedIndexes.Count);

                unmodifiedUids = inbox.SetFlags(uids, modseq, MessageFlags.Seen, true);
                Assert.AreEqual(0, unmodifiedUids.Count);

                var labels = new string[] { "Label1", "Label2" };

                // AddLabels
                unmodifiedIndexes = inbox.AddLabels(indexes, modseq, labels, true);
                Assert.AreEqual(0, unmodifiedIndexes.Count);

                unmodifiedUids = inbox.AddLabels(uids, modseq, labels, true);
                Assert.AreEqual(0, unmodifiedUids.Count);

                // RemoveLabels
                unmodifiedIndexes = inbox.RemoveLabels(indexes, modseq, labels, true);
                Assert.AreEqual(0, unmodifiedIndexes.Count);

                unmodifiedUids = inbox.RemoveLabels(uids, modseq, labels, true);
                Assert.AreEqual(0, unmodifiedUids.Count);

                // SetLabels
                unmodifiedIndexes = inbox.SetLabels(indexes, modseq, labels, true);
                Assert.AreEqual(0, unmodifiedIndexes.Count);

                unmodifiedUids = inbox.SetLabels(uids, modseq, labels, true);
                Assert.AreEqual(0, unmodifiedUids.Count);

                client.Disconnect(false);
            }
        }
Ejemplo n.º 54
0
 public IdleClient()
 {
     client   = new ImapClient(new ProtocolLogger(Console.OpenStandardError()));
     messages = new List <IMessageSummary> ();
     cancel   = new CancellationTokenSource();
 }
Ejemplo n.º 55
0
        public void TestImapClientGMail()
        {
            var commands = new List <ImapReplayCommand> ();

            commands.Add(new ImapReplayCommand("", "gmail.greeting.txt"));
            commands.Add(new ImapReplayCommand("A00000000 CAPABILITY\r\n", "gmail.capability.txt"));
            commands.Add(new ImapReplayCommand("A00000001 AUTHENTICATE PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "gmail.authenticate.txt"));
            commands.Add(new ImapReplayCommand("A00000002 NAMESPACE\r\n", "gmail.namespace.txt"));
            commands.Add(new ImapReplayCommand("A00000003 LIST \"\" \"INBOX\"\r\n", "gmail.list-inbox.txt"));
            commands.Add(new ImapReplayCommand("A00000004 XLIST \"\" \"*\"\r\n", "gmail.xlist.txt"));
            commands.Add(new ImapReplayCommand("A00000005 LIST \"\" \"%\"\r\n", "gmail.list-personal.txt"));
            commands.Add(new ImapReplayCommand("A00000006 CREATE UnitTests\r\n", "gmail.create-unittests.txt"));
            commands.Add(new ImapReplayCommand("A00000007 LIST \"\" UnitTests\r\n", "gmail.list-unittests.txt"));
            commands.Add(new ImapReplayCommand("A00000008 SELECT UnitTests (CONDSTORE)\r\n", "gmail.select-unittests.txt"));

            for (int i = 0; i < 50; i++)
            {
                using (var stream = GetResourceStream(string.Format("common.message.{0}.msg", i))) {
                    var    message = MimeMessage.Load(stream);
                    long   length  = stream.Length;
                    string latin1;

                    stream.Position = 0;
                    using (var reader = new StreamReader(stream, Latin1))
                        latin1 = reader.ReadToEnd();

                    var command = string.Format("A{0:D8} APPEND UnitTests (\\Seen) ", i + 9);
                    command += "{" + length + "}\r\n";

                    commands.Add(new ImapReplayCommand(command, "gmail.go-ahead.txt"));
                    commands.Add(new ImapReplayCommand(latin1 + "\r\n", string.Format("gmail.append.{0}.txt", i + 1)));
                }
            }

            commands.Add(new ImapReplayCommand("A00000059 UID SEARCH RETURN () CHARSET US-ASCII OR TO nsb CC nsb\r\n", "gmail.search.txt"));
            commands.Add(new ImapReplayCommand("A00000060 UID FETCH 1:3,5,7:9,11:14,26:29,31,34,41:43,50 (UID FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY)\r\n", "gmail.search-summary.txt"));
            commands.Add(new ImapReplayCommand("A00000061 UID FETCH 1 (BODY.PEEK[])\r\n", "gmail.fetch.1.txt"));
            commands.Add(new ImapReplayCommand("A00000062 UID FETCH 2 (BODY.PEEK[])\r\n", "gmail.fetch.2.txt"));
            commands.Add(new ImapReplayCommand("A00000063 UID FETCH 3 (BODY.PEEK[])\r\n", "gmail.fetch.3.txt"));
            commands.Add(new ImapReplayCommand("A00000064 UID FETCH 5 (BODY.PEEK[])\r\n", "gmail.fetch.5.txt"));
            commands.Add(new ImapReplayCommand("A00000065 UID FETCH 7 (BODY.PEEK[])\r\n", "gmail.fetch.7.txt"));
            commands.Add(new ImapReplayCommand("A00000066 UID FETCH 8 (BODY.PEEK[])\r\n", "gmail.fetch.8.txt"));
            commands.Add(new ImapReplayCommand("A00000067 UID FETCH 9 (BODY.PEEK[])\r\n", "gmail.fetch.9.txt"));
            commands.Add(new ImapReplayCommand("A00000068 UID FETCH 11 (BODY.PEEK[])\r\n", "gmail.fetch.11.txt"));
            commands.Add(new ImapReplayCommand("A00000069 UID FETCH 12 (BODY.PEEK[])\r\n", "gmail.fetch.12.txt"));
            commands.Add(new ImapReplayCommand("A00000070 UID FETCH 13 (BODY.PEEK[])\r\n", "gmail.fetch.13.txt"));
            commands.Add(new ImapReplayCommand("A00000071 UID FETCH 14 (BODY.PEEK[])\r\n", "gmail.fetch.14.txt"));
            commands.Add(new ImapReplayCommand("A00000072 UID FETCH 26 (BODY.PEEK[])\r\n", "gmail.fetch.26.txt"));
            commands.Add(new ImapReplayCommand("A00000073 UID FETCH 27 (BODY.PEEK[])\r\n", "gmail.fetch.27.txt"));
            commands.Add(new ImapReplayCommand("A00000074 UID FETCH 28 (BODY.PEEK[])\r\n", "gmail.fetch.28.txt"));
            commands.Add(new ImapReplayCommand("A00000075 UID FETCH 29 (BODY.PEEK[])\r\n", "gmail.fetch.29.txt"));
            commands.Add(new ImapReplayCommand("A00000076 UID FETCH 31 (BODY.PEEK[])\r\n", "gmail.fetch.31.txt"));
            commands.Add(new ImapReplayCommand("A00000077 UID FETCH 34 (BODY.PEEK[])\r\n", "gmail.fetch.34.txt"));
            commands.Add(new ImapReplayCommand("A00000078 UID FETCH 41 (BODY.PEEK[])\r\n", "gmail.fetch.41.txt"));
            commands.Add(new ImapReplayCommand("A00000079 UID FETCH 42 (BODY.PEEK[])\r\n", "gmail.fetch.42.txt"));
            commands.Add(new ImapReplayCommand("A00000080 UID FETCH 43 (BODY.PEEK[])\r\n", "gmail.fetch.43.txt"));
            commands.Add(new ImapReplayCommand("A00000081 UID FETCH 50 (BODY.PEEK[])\r\n", "gmail.fetch.50.txt"));
            commands.Add(new ImapReplayCommand("A00000082 UID STORE 1:3,5,7:9,11:14,26:29,31,34,41:43,50 FLAGS (\\Answered \\Seen)\r\n", "gmail.set-flags.txt"));
            commands.Add(new ImapReplayCommand("A00000083 UID STORE 1:3,5,7:9,11:14,26:29,31,34,41:43,50 -FLAGS.SILENT (\\Answered)\r\n", "gmail.remove-flags.txt"));
            commands.Add(new ImapReplayCommand("A00000084 UID STORE 1:3,5,7:9,11:14,26:29,31,34,41:43,50 +FLAGS.SILENT (\\Deleted)\r\n", "gmail.add-flags.txt"));
            commands.Add(new ImapReplayCommand("A00000085 UNSELECT\r\n", "gmail.unselect-unittests.txt"));
            commands.Add(new ImapReplayCommand("A00000086 DELETE UnitTests\r\n", "gmail.delete-unittests.txt"));
            commands.Add(new ImapReplayCommand("A00000087 LOGOUT\r\n", "gmail.logout.txt"));

            using (var client = new ImapClient()) {
                try {
                    client.ReplayConnect("localhost", new ImapReplayStream(commands, false), CancellationToken.None);
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Connect: {0}", ex);
                }

                Assert.IsTrue(client.IsConnected, "Client failed to connect.");

                Assert.AreEqual(GMailInitialCapabilities, client.Capabilities);
                Assert.AreEqual(4, client.AuthenticationMechanisms.Count);
                Assert.IsTrue(client.AuthenticationMechanisms.Contains("XOAUTH"), "Expected SASL XOAUTH auth mechanism");
                Assert.IsTrue(client.AuthenticationMechanisms.Contains("XOAUTH2"), "Expected SASL XOAUTH2 auth mechanism");
                Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism");
                Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN-CLIENTTOKEN"), "Expected SASL PLAIN-CLIENTTOKEN auth mechanism");

                try {
                    var credentials = new NetworkCredential("username", "password");

                    // Note: Do not try XOAUTH2
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    client.Authenticate(credentials, CancellationToken.None);
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Authenticate: {0}", ex);
                }

                Assert.AreEqual(GMailAuthenticatedCapabilities, client.Capabilities);

                var inbox = client.Inbox;
                Assert.IsNotNull(inbox, "Expected non-null Inbox folder.");
                Assert.AreEqual(FolderAttributes.HasNoChildren, inbox.Attributes, "Expected Inbox attributes to be \\HasNoChildren.");

                foreach (var special in Enum.GetValues(typeof(SpecialFolder)).OfType <SpecialFolder> ())
                {
                    var folder = client.GetFolder(special);

                    if (special != SpecialFolder.Archive)
                    {
                        var expected = GetSpecialFolderAttribute(special) | FolderAttributes.HasNoChildren;

                        Assert.IsNotNull(folder, "Expected non-null {0} folder.", special);
                        Assert.AreEqual(expected, folder.Attributes, "Expected {0} attributes to be \\HasNoChildren.", special);
                    }
                    else
                    {
                        Assert.IsNull(folder, "Expected null {0} folder.", special);
                    }
                }

                var personal = client.GetFolder(client.PersonalNamespaces[0]);
                var folders  = personal.GetSubfolders(false, CancellationToken.None).ToList();
                Assert.AreEqual(client.Inbox, folders[0], "Expected the first folder to be the Inbox.");
                Assert.AreEqual("[Gmail]", folders[1].FullName, "Expected the second folder to be [Gmail].");
                Assert.AreEqual(FolderAttributes.NoSelect | FolderAttributes.HasChildren, folders[1].Attributes, "Expected [Gmail] folder to be \\Noselect \\HasChildren.");

                var created = personal.Create("UnitTests", true, CancellationToken.None);

                Assert.IsNotNull(created.ParentFolder, "The ParentFolder property should not be null.");

                created.Open(FolderAccess.ReadWrite, CancellationToken.None);

                for (int i = 0; i < 50; i++)
                {
                    using (var stream = GetResourceStream(string.Format("common.message.{0}.msg", i))) {
                        var message = MimeMessage.Load(stream);

                        created.Append(message, MessageFlags.Seen, CancellationToken.None);
                    }
                }

                var query   = SearchQuery.ToContains("nsb").Or(SearchQuery.CcContains("nsb"));
                var matches = created.Search(query, CancellationToken.None);

                const MessageSummaryItems items = MessageSummaryItems.Full | MessageSummaryItems.UniqueId;
                var summaries = created.Fetch(matches, items, CancellationToken.None);

                foreach (var summary in summaries)
                {
                    created.GetMessage(summary.UniqueId, CancellationToken.None);
                }

                created.SetFlags(matches, MessageFlags.Seen | MessageFlags.Answered, false, CancellationToken.None);
                created.RemoveFlags(matches, MessageFlags.Answered, true, CancellationToken.None);
                created.AddFlags(matches, MessageFlags.Deleted, true, CancellationToken.None);

                created.Close(false, CancellationToken.None);
                created.Delete(CancellationToken.None);

                client.Disconnect(true, CancellationToken.None);
            }
        }
Ejemplo n.º 56
0
 private ImapMailBox()
 {
     _client = new ImapClient();
 }
Ejemplo n.º 57
0
 public GMailClient()
 {
     NewMessages = new ObservableCollection <MailMessage>();
     _client     = new ImapClient(ServerUrl, ServerPort, useSsl: ServerUsesSsl, validateServerCertificate: true);
 }
Ejemplo n.º 58
0
        public IList <EmailMessage> GetNewMessages(int accountId)
        {
            var account     = _context.Accounts.Include(a => a.EmailAccount).FirstOrDefault(a => a.Id == accountId);
            var newMessages = new List <EmailMessage>();

            if (account != null)
            {
                EmailAccount eAcc = account.EmailAccount;

                using (var client = new ImapClient())
                {
                    var credentials = new NetworkCredential(eAcc.UserName, eAcc.Password);

                    client.Connect(eAcc.ServerUri, eAcc.ServerPort, eAcc.ServerUseSSL);

                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    client.Authenticate(credentials);

                    client.Inbox.Open(FolderAccess.ReadOnly);

                    // Обрабатываем сами письма

                    foreach (var summary in client.Inbox.Fetch((int)eAcc.LastMessageUid, -1, MessageSummaryItems.UniqueId))
                    {
                        MimeMessage iMessage = client.Inbox.GetMessage(summary.UniqueId);

                        // Если в белом списке есть запись "*", то принимаем письма от всех отправителей
                        if (eAcc.WhileListFrom.Contains("*") || eAcc.WhileListFrom.Contains(iMessage.From.Mailboxes.First().Address))
                        {
                            // Текстовое содержимое

                            var message = new EmailMessage
                            {
                                Id           = (int)summary.UniqueId.Id,
                                From         = iMessage.From.Mailboxes.First().Name,
                                Subject      = iMessage.Subject,
                                Body         = iMessage.TextBody,
                                ReceivedDate = iMessage.Date.LocalDateTime
                            };

                            // Вложения

                            var multiparts  = new List <Multipart>();
                            var attachments = new List <MimePart>();
                            using (var iter = new MimeIterator(iMessage))
                            {
                                while (iter.MoveNext())
                                {
                                    var multipart = iter.Parent as Multipart;
                                    var part      = iter.Current as MimePart;

                                    if (multipart != null && part != null && part.IsAttachment)
                                    {
                                        multiparts.Add(multipart);
                                        attachments.Add(part);
                                    }
                                }
                            }

                            for (int i = 0; i < attachments.Count; i++)
                            {
                                multiparts[i].Remove(attachments[i]);
                            }

                            foreach (var attachment in attachments)
                            {
                                using (var ms = new MemoryStream())
                                {
                                    attachment.ContentObject.DecodeTo(ms);

                                    message.Attachments.Add(new Attachment
                                    {
                                        Title    = attachment.FileName,
                                        Contents = ms.ToArray()
                                    });
                                }
                            }

                            newMessages.Add(message);
                        }

                        eAcc.LastMessageUid = (int)summary.UniqueId.Id; // Учитываем Id сообщения, даже если оно не подошло
                    }
                }

                _context.SaveChanges();
            }

            return(newMessages);
        }
Ejemplo n.º 59
0
 static Mail()
 {
     Client = new ImapClient();
 }
Ejemplo n.º 60
0
 public MailFolderFinder(
     Func <ImapClient, Func <string, IEnumerable <IMailFolder> > > findByName,
     ImapClient client)
 {
     this.getFolderByName = findByName(client);
 }