Пример #1
0
        public IList<Stream> Load(Mailbox mailbox)
        {
            IList<Stream> result = new List<Stream>();

            using (var client = new Pop3Client())
            {
                client.Connect(mailbox.Server, mailbox.Port, mailbox.Ssl);
                client.Authenticate(mailbox.Username, mailbox.Password);

                var msgCount = client.Count;
                Console.WriteLine("[{2}] - [{1}] {0} new messages found", msgCount, mailbox.Username, DateTime.Now);

                for (var li = 0; li < msgCount; li++)
                {
                    try
                    {
                        var letter = client.GetMessage(li);

                        var parts = letter.BodyParts;
                        foreach (var part in parts)
                        {
                            if (part.IsAttachment)
                            {
                                var stream = new MemoryStream();
                                ((MimePart)part).ContentObject.WriteTo(stream);
                                stream.Position = 0;
                                result.Add(stream);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Message recieve error: {0}", ex.Message);
                    }
                    finally
                    {
                        client.DeleteMessage(li);
                    }
                }
                client.Disconnect(true);
            }

            return result;
        }
Пример #2
0
        /*
         * returns message count from pop3 server
         */
        internal static int GetMessageCount(Core.Node ip, Core.Node dp)
        {
            string host = Expressions.GetExpressionValue<string>(ip.GetValue("host", ""), dp, ip, false);
            int port = Expressions.GetExpressionValue<int>(ip.GetValue("port", "-1"), dp, ip, false);
            bool implicitSsl = Expressions.GetExpressionValue<bool>(ip.GetValue("ssl", "false"), dp, ip, false);
            string username = Expressions.GetExpressionValue<string>(ip.GetValue("username", ""), dp, ip, false);
            string password = Expressions.GetExpressionValue<string>(ip.GetValue("password", ""), dp, ip, false);

            using (Pop3Client client = new Pop3Client())
            {
                client.Connect(host, port, implicitSsl);
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                if (!string.IsNullOrEmpty(username))
                    client.Authenticate(username, password);
                int retVal = client.GetMessageCount();
                client.Disconnect(true);
                return retVal;
            }
        }
Пример #3
0
		public static void DownloadMessages ()
		{
			using (var client = new Pop3Client (new ProtocolLogger ("pop3.log"))) {
				client.Connect ("pop.gmail.com", 995, SecureSocketOptions.SslOnConnect);

				client.Authenticate ("username", "password");

				for (int i = 0; i < client.Count; i++) {
					var message = client.GetMessage (i);

					// write the message to a file
					message.WriteTo (string.Format ("{0}.msg", i));

					// mark the message for deletion
					client.DeleteMessage (i);
				}

				client.Disconnect (true);
			}
		}
Пример #4
0
        public void TestAuthenticationExceptions()
        {
            var commands = new List<Pop3ReplayCommand> ();
            commands.Add (new Pop3ReplayCommand ("", "comcast.greeting.txt"));
            commands.Add (new Pop3ReplayCommand ("CAPA\r\n", "comcast.capa1.txt"));
            commands.Add (new Pop3ReplayCommand ("USER username\r\n", "comcast.ok.txt"));
            commands.Add (new Pop3ReplayCommand ("PASS password\r\n", "comcast.err.txt"));
            commands.Add (new Pop3ReplayCommand ("QUIT\r\n", "comcast.quit.txt"));

            using (var client = new Pop3Client ()) {
                try {
                    client.ReplayConnect ("localhost", new Pop3ReplayStream (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 (ComcastCapa1, client.Capabilities);
                Assert.AreEqual (0, client.AuthenticationMechanisms.Count);
                Assert.AreEqual (31, client.ExpirePolicy);

                try {
                    var credentials = new NetworkCredential ("username", "password");
                    client.Authenticate (credentials, CancellationToken.None);
                    Assert.Fail ("Expected AuthenticationException");
                } catch (AuthenticationException) {
                    // we expect this exception...
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
                }

                Assert.IsTrue (client.IsConnected, "AuthenticationException should not cause a disconnect.");

                try {
                    var count = client.GetMessageCount (CancellationToken.None);
                    Assert.Fail ("Expected UnauthorizedAccessException");
                } catch (UnauthorizedAccessException) {
                    // we expect this exception...
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in Count: {0}", ex);
                }

                Assert.IsTrue (client.IsConnected, "UnauthorizedAccessException should not cause a disconnect.");

                try {
                    var sizes = client.GetMessageSizes (CancellationToken.None);
                    Assert.Fail ("Expected UnauthorizedAccessException");
                } catch (UnauthorizedAccessException) {
                    // we expect this exception...
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in GetMessageSizes: {0}", ex);
                }

                Assert.IsTrue (client.IsConnected, "UnauthorizedAccessException should not cause a disconnect.");

                try {
                    var size = client.GetMessageSize ("uid", CancellationToken.None);
                    Assert.Fail ("Expected UnauthorizedAccessException");
                } catch (UnauthorizedAccessException) {
                    // we expect this exception...
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in GetMessageSize(uid): {0}", ex);
                }

                Assert.IsTrue (client.IsConnected, "UnauthorizedAccessException should not cause a disconnect.");

                try {
                    var size = client.GetMessageSize (0, CancellationToken.None);
                    Assert.Fail ("Expected UnauthorizedAccessException");
                } catch (UnauthorizedAccessException) {
                    // we expect this exception...
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in GetMessageSize(int): {0}", ex);
                }

                Assert.IsTrue (client.IsConnected, "UnauthorizedAccessException should not cause a disconnect.");

                try {
                    var uids = client.GetMessageUids (CancellationToken.None);
                    Assert.Fail ("Expected UnauthorizedAccessException");
                } catch (UnauthorizedAccessException) {
                    // we expect this exception...
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in GetMessageUids: {0}", ex);
                }

                Assert.IsTrue (client.IsConnected, "UnauthorizedAccessException should not cause a disconnect.");

                try {
                    var uid = client.GetMessageUid (0, CancellationToken.None);
                    Assert.Fail ("Expected UnauthorizedAccessException");
                } catch (UnauthorizedAccessException) {
                    // we expect this exception...
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in GetMessageUid: {0}", ex);
                }

                Assert.IsTrue (client.IsConnected, "UnauthorizedAccessException should not cause a disconnect.");

                try {
                    var message = client.GetMessage ("uid", CancellationToken.None);
                    Assert.Fail ("Expected UnauthorizedAccessException");
                } catch (UnauthorizedAccessException) {
                    // we expect this exception...
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in GetMessage(uid): {0}", ex);
                }

                Assert.IsTrue (client.IsConnected, "UnauthorizedAccessException should not cause a disconnect.");

                try {
                    var message = client.GetMessage (0, CancellationToken.None);
                    Assert.Fail ("Expected UnauthorizedAccessException");
                } catch (UnauthorizedAccessException) {
                    // we expect this exception...
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in GetMessage(int): {0}", ex);
                }

                Assert.IsTrue (client.IsConnected, "UnauthorizedAccessException should not cause a disconnect.");

                try {
                    client.DeleteMessage ("uid", CancellationToken.None);
                    Assert.Fail ("Expected UnauthorizedAccessException");
                } catch (UnauthorizedAccessException) {
                    // we expect this exception...
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in DeleteMessage(uid): {0}", ex);
                }

                Assert.IsTrue (client.IsConnected, "UnauthorizedAccessException should not cause a disconnect.");

                try {
                    client.DeleteMessage (0, CancellationToken.None);
                    Assert.Fail ("Expected UnauthorizedAccessException");
                } catch (UnauthorizedAccessException) {
                    // we expect this exception...
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in DeleteMessage(int): {0}", ex);
                }

                Assert.IsTrue (client.IsConnected, "UnauthorizedAccessException should not cause a disconnect.");

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

                Assert.IsFalse (client.IsConnected, "Failed to disconnect");
            }
        }
Пример #5
0
        public void TestGMailPop3Client()
        {
            var commands = new List<Pop3ReplayCommand> ();
            commands.Add (new Pop3ReplayCommand ("", "gmail.greeting.txt"));
            commands.Add (new Pop3ReplayCommand ("CAPA\r\n", "gmail.capa1.txt"));
            commands.Add (new Pop3ReplayCommand ("AUTH PLAIN\r\n", "gmail.plus.txt"));
            commands.Add (new Pop3ReplayCommand ("AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "gmail.auth.txt"));
            commands.Add (new Pop3ReplayCommand ("CAPA\r\n", "gmail.capa2.txt"));
            commands.Add (new Pop3ReplayCommand ("STAT\r\n", "gmail.stat.txt"));
            commands.Add (new Pop3ReplayCommand ("RETR 1\r\n", "gmail.retr1.txt"));
            commands.Add (new Pop3ReplayCommand ("QUIT\r\n", "gmail.quit.txt"));

            using (var client = new Pop3Client ()) {
                try {
                    client.ReplayConnect ("localhost", new Pop3ReplayStream (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 (GMailCapa1, client.Capabilities);
                Assert.AreEqual (2, client.AuthenticationMechanisms.Count);
                Assert.IsTrue (client.AuthenticationMechanisms.Contains ("XOAUTH2"), "Expected SASL XOAUTH2 auth mechanism");
                Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Expected SASL PLAIN auth mechanism");

                // Note: remove the XOAUTH2 auth mechanism to force PLAIN auth
                client.AuthenticationMechanisms.Remove ("XOAUTH2");

                try {
                    var credentials = new NetworkCredential ("username", "password");
                    client.Authenticate (credentials, CancellationToken.None);
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
                }

                Assert.AreEqual (GMailCapa2, client.Capabilities);
                Assert.AreEqual (0, client.AuthenticationMechanisms.Count);

                try {
                    var count = client.GetMessageCount (CancellationToken.None);
                    Assert.AreEqual (1, count, "Expected 1 message");
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in GetMessageCount: {0}", ex);
                }

            //				try {
            //					var uids = client.GetMessageUids (CancellationToken.None);
            //					Assert.AreEqual (7, uids.Length, "Expected 7 uids");
            //				} catch (Exception ex) {
            //					Assert.Fail ("Did not expect an exception in GetMessageUids: {0}", ex);
            //				}

                try {
                    var message = client.GetMessage (0, CancellationToken.None);

                    using (var jpeg = new MemoryStream ()) {
                        var attachment = message.Attachments.FirstOrDefault ();

                        attachment.ContentObject.DecodeTo (jpeg);
                        jpeg.Position = 0;

                        using (var md5 = new MD5CryptoServiceProvider ()) {
                            var md5sum = HexEncode (md5.ComputeHash (jpeg));

                            Assert.AreEqual ("5b1b8b2c9300c9cd01099f44e1155e2b", md5sum, "MD5 checksums do not match.");
                        }
                    }
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in GetMessage: {0}", ex);
                }

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

                Assert.IsFalse (client.IsConnected, "Failed to disconnect");
            }
        }
Пример #6
0
        public void TestExchangePop3Client()
        {
            var commands = new List<Pop3ReplayCommand> ();
            commands.Add (new Pop3ReplayCommand ("", "exchange.greeting.txt"));
            commands.Add (new Pop3ReplayCommand ("CAPA\r\n", "exchange.capa.txt"));
            commands.Add (new Pop3ReplayCommand ("AUTH PLAIN\r\n", "exchange.plus.txt"));
            commands.Add (new Pop3ReplayCommand ("AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "exchange.auth.txt"));
            commands.Add (new Pop3ReplayCommand ("CAPA\r\n", "exchange.capa.txt"));
            commands.Add (new Pop3ReplayCommand ("STAT\r\n", "exchange.stat.txt"));
            commands.Add (new Pop3ReplayCommand ("UIDL\r\n", "exchange.uidl.txt"));
            commands.Add (new Pop3ReplayCommand ("RETR 1\r\n", "exchange.retr1.txt"));
            commands.Add (new Pop3ReplayCommand ("QUIT\r\n", "exchange.quit.txt"));

            using (var client = new Pop3Client ()) {
                try {
                    client.ReplayConnect ("localhost", new Pop3ReplayStream (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 (ExchangeCapa, client.Capabilities);
                Assert.AreEqual (3, client.AuthenticationMechanisms.Count);
                Assert.IsTrue (client.AuthenticationMechanisms.Contains ("GSSAPI"), "Expected SASL GSSAPI auth mechanism");
                Assert.IsTrue (client.AuthenticationMechanisms.Contains ("NTLM"), "Expected SASL NTLM auth mechanism");
                Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Expected SASL PLAIN auth mechanism");

                // Note: remove these auth mechanisms to force PLAIN auth
                client.AuthenticationMechanisms.Remove ("GSSAPI");
                client.AuthenticationMechanisms.Remove ("NTLM");

                try {
                    var credentials = new NetworkCredential ("username", "password");
                    client.Authenticate (credentials, CancellationToken.None);
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
                }

                Assert.AreEqual (ExchangeCapa, client.Capabilities);
                Assert.AreEqual (3, client.AuthenticationMechanisms.Count);
                Assert.IsTrue (client.AuthenticationMechanisms.Contains ("GSSAPI"), "Expected SASL GSSAPI auth mechanism");
                Assert.IsTrue (client.AuthenticationMechanisms.Contains ("NTLM"), "Expected SASL NTLM auth mechanism");
                Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Expected SASL PLAIN auth mechanism");

                try {
                    var count = client.GetMessageCount (CancellationToken.None);
                    Assert.AreEqual (7, count, "Expected 7 messages");
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in GetMessageCount: {0}", ex);
                }

                try {
                    var uids = client.GetMessageUids (CancellationToken.None);
                    Assert.AreEqual (7, uids.Count, "Expected 7 uids");
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in GetMessageUids: {0}", ex);
                }

                try {
                    var message = client.GetMessage (0, CancellationToken.None);
                    // TODO: assert that the message is byte-identical to what we expect
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in GetMessage: {0}", ex);
                }

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

                Assert.IsFalse (client.IsConnected, "Failed to disconnect");
            }
        }
Пример #7
0
        public void TestBasicPop3ClientUnixLineEndings()
        {
            var commands = new List<Pop3ReplayCommand> ();
            commands.Add (new Pop3ReplayCommand ("", "comcast.greeting.txt"));
            commands.Add (new Pop3ReplayCommand ("CAPA\r\n", "comcast.capa1.txt"));
            commands.Add (new Pop3ReplayCommand ("USER username\r\n", "comcast.ok.txt"));
            commands.Add (new Pop3ReplayCommand ("PASS password\r\n", "comcast.ok.txt"));
            commands.Add (new Pop3ReplayCommand ("CAPA\r\n", "comcast.capa2.txt"));
            commands.Add (new Pop3ReplayCommand ("STAT\r\n", "comcast.stat1.txt"));
            commands.Add (new Pop3ReplayCommand ("RETR 1\r\n", "comcast.retr1.txt"));
            commands.Add (new Pop3ReplayCommand ("QUIT\r\n", "comcast.quit.txt"));

            using (var client = new Pop3Client ()) {
                try {
                    client.ReplayConnect ("localhost", new Pop3ReplayStream (commands, true), 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 (ComcastCapa1, client.Capabilities);
                Assert.AreEqual (0, client.AuthenticationMechanisms.Count);
                Assert.AreEqual (31, client.ExpirePolicy);

                try {
                    var credentials = new NetworkCredential ("username", "password");
                    client.Authenticate (credentials, CancellationToken.None);
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
                }

                Assert.AreEqual (ComcastCapa2, client.Capabilities);
                Assert.AreEqual ("ZimbraInc", client.Implementation);
                Assert.AreEqual (2, client.AuthenticationMechanisms.Count);
                Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Expected SASL PLAIN auth mechanism");
                Assert.IsTrue (client.AuthenticationMechanisms.Contains ("X-ZIMBRA"), "Expected SASL X-ZIMBRA auth mechanism");
                Assert.AreEqual (-1, client.ExpirePolicy);

                try {
                    var count = client.GetMessageCount (CancellationToken.None);
                    Assert.AreEqual (1, count, "Expected 1 message");
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in Count: {0}", ex);
                }

                try {
                    var message = client.GetMessage (0, CancellationToken.None);
                    // TODO: assert that the message is byte-identical to what we expect
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in GetMessage: {0}", ex);
                }

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

                Assert.IsFalse (client.IsConnected, "Failed to disconnect");
            }
        }
Пример #8
0
        /*
         * returns messages from pop3 server
         */
        internal static void GetMessages(
            Node pars,
            Node ip,
            Node dp,
            string basePath,
            string attachmentDirectory,
            string linkedAttachmentDirectory)
        {
            string host = Expressions.GetExpressionValue<string>(ip.GetValue("host", ""), dp, ip, false);
            int port = Expressions.GetExpressionValue<int>(ip.GetValue("port", "-1"), dp, ip, false);
            bool implicitSsl = Expressions.GetExpressionValue<bool>(ip.GetValue("ssl", "false"), dp, ip, false);
            string username = Expressions.GetExpressionValue<string>(ip.GetValue("username", ""), dp, ip, false);
            string password = Expressions.GetExpressionValue<string>(ip.GetValue("password", ""), dp, ip, false);

            Node exeNode = null;
            if (ip.Contains("code"))
                exeNode = ip["code"];

            using (Pop3Client client = new Pop3Client())
            {
                client.Connect(host, port, implicitSsl);
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                if (!string.IsNullOrEmpty(username))
                    client.Authenticate(username, password);

                try
                {
                    RetrieveMessagesFromServer(
                        pars,
                        dp,
                        ip,
                        basePath,
                        attachmentDirectory,
                        linkedAttachmentDirectory,
                        exeNode,
                        client);
                }
                finally
                {
                    if (client.IsConnected)
                        client.Disconnect(true);
                }
            }
        }
Пример #9
0
        public RC getMessages(bool bUsePop3 = false, int iPortToUse = 0)
        {
            try
            {
                if (bUsePop3) {
                    using (var client = new Pop3Client ()) {

                        if (iPortToUse == 0) {
                            client.Connect (m_EmailServiceDescription.Pop3Url, 110, true);
                        } else {
                            client.Connect (m_EmailServiceDescription.Pop3Url, iPortToUse, true);
                        }

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

                        client.Authenticate (m_AuthInfo.m_sId, m_AuthInfo.m_sPassword);

                        for (int i = 0; i < client.Count; i++) {
                            var message = client.GetMessage (i);
                            string sPlainBody = m_OpenPgpCrypter.DecryptPgpString(message.GetTextBody(MimeKit.Text.TextFormat.Text));
                            m_ConversationManager.addMessage (m_sProtocol, message.Subject + " " + sPlainBody, message.Sender.Address, m_AuthInfo.m_sId);
                        }

                        client.Disconnect(true);
                        return RC.RC_OK;
                    }
                }
                else //use IMAP
                {
                    using (var client = new ImapClient ()) {

                        if (iPortToUse == 0) {
                            client.Connect (m_EmailServiceDescription.ImapUrl, 993, true);
                        } else {
                            client.Connect (m_EmailServiceDescription.ImapUrl, iPortToUse, true);
                        }

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

                        client.Authenticate (m_AuthInfo.m_sId, m_AuthInfo.m_sPassword);

                        // The Inbox folder is always available on all IMAP servers...
                        var inbox = client.Inbox;
                        inbox.Open (FolderAccess.ReadOnly);

                        //TODO: delete writeline
                        Console.WriteLine ("Total messages: {0}", inbox.Count);
                        Console.WriteLine ("Recent messages: {0}", inbox.Recent);

                        for (int i = 0; i < inbox.Count; i++) {
                            var message = inbox.GetMessage (i);
                            m_ConversationManager.addMessage (m_sProtocol, message.Subject + message.Body, message.Sender.Address, m_AuthInfo.m_sId);
                        }

                        client.Disconnect (true);
                        return RC.RC_OK;
                    }
                }
            }
            catch(Exception e) {
                m_Logger.log (ELogLevel.LVL_WARNING, e.Message, m_sModuleName);
                return RC.RC_INBOX_NOT_AVAILABLE;
            }
        }
Пример #10
0
		public static void PrintCapabilities ()
		{
			using (var client = new Pop3Client ()) {
				client.Connect ("pop.gmail.com", 995, SecureSocketOptions.SslOnConnect);

				if (client.Capabilities.HasFlag (Pop3Capabilities.SASL)) {
					var mechanisms = string.Join (", ", client.AuthenticationMechanisms);
					Console.WriteLine ("The POP3 server supports the following SASL mechanisms: {0}", mechanisms);

					// Note: if we don't want MailKit to use a particular SASL mechanism, we can disable it like this:
					client.AuthenticationMechanisms.Remove ("XOAUTH2");
				}

				client.Authenticate ("username", "password");

				if (client.Capabilities.HasFlag (Pop3Capabilities.Apop))
					Console.WriteLine ("The server supports APOP authentication.");

				if (client.Capabilities.HasFlag (Pop3Capabilities.Expire)) {
					if (client.ExpirePolicy > 0)
						Console.WriteLine ("The POP3 server automatically expires messages after {0} days", client.ExpirePolicy);
					else
						Console.WriteLine ("The POP3 server will never expire messages.");
				}

				if (client.Capabilities.HasFlag (Pop3Capabilities.LoginDelay))
					Console.WriteLine ("The minimum number of seconds between login attempts is {0}.", client.LoginDelay);

				if (client.Capabilities.HasFlag (Pop3Capabilities.Pipelining))
					Console.WriteLine ("The POP3 server can pipeline commands, so using client.GetMessages() will be faster.");

				if (client.Capabilities.HasFlag (Pop3Capabilities.Top))
					Console.WriteLine ("The POP3 server supports the TOP command, so it's possible to download message headers.");

				if (client.Capabilities.HasFlag (Pop3Capabilities.UIDL))
					Console.WriteLine ("The POP3 server supports the UIDL command which means we can track messages by UID.");

				client.Disconnect (true);
			}
		}
Пример #11
0
		public static void DownloadNewMessages (HashSet<string> previouslyDownloadedUids)
		{
			using (var client = new Pop3Client ()) {
				IList<string> uids = null;

				try {
					client.Connect ("pop.gmail.com", 995, SecureSocketOptions.SslOnConnect);
				} catch (Pop3CommandException ex) {
					Console.WriteLine ("Error trying to connect: {0}", ex.Message);
					Console.WriteLine ("\tStatusText: {0}", ex.StatusText);
					return;
				} catch (Pop3ProtocolException ex) {
					Console.WriteLine ("Protocol error while trying to connect: {0}", ex.Message);
					return;
				}

				try {
					client.Authenticate ("username", "password");
				} catch (AuthenticationException ex) {
					Console.WriteLine ("Invalid user name or password.");
					return;
				} catch (Pop3CommandException ex) {
					Console.WriteLine ("Error trying to authenticate: {0}", ex.Message);
					Console.WriteLine ("\tStatusText: {0}", ex.StatusText);
					return;
				} catch (Pop3ProtocolException ex) {
					Console.WriteLine ("Protocol error while trying to authenticate: {0}", ex.Message);
					return;
				}

				// for the sake of this example, let's assume GMail supports the UIDL extension
				if (client.Capabilities.HasFlag (Pop3Capabilities.UIDL)) {
					try {
						uids = client.GetMessageUids ();
					} catch (Pop3CommandException ex) {
						Console.WriteLine ("Error trying to get the list of uids: {0}", ex.Message);
						Console.WriteLine ("\tStatusText: {0}", ex.StatusText);

						// we'll continue on leaving uids set to null...
					} catch (Pop3ProtocolException ex) {
						Console.WriteLine ("Protocol error while trying to authenticate: {0}", ex.Message);

						// Pop3ProtocolExceptions often cause the connection to drop
						if (!client.IsConnected)
							return;
					}
				}

				for (int i = 0; i < client.Count; i++) {
					if (uids != null && previouslyDownloadedUids.Contains (uids[i])) {
						// we must have downloaded this message in a previous session
						continue;
					}

					try {
						// download the message at the specified index
						var message = client.GetMessage (i);

						// write the message to a file
						if (uids != null) {
							message.WriteTo (string.Format ("{0}.msg", uids[i]));

							// keep track of our downloaded message uids so we can skip downloading them next time
							previouslyDownloadedUids.Add (uids[i]);
						} else {
							message.WriteTo (string.Format ("{0}.msg", i));
						}
					} catch (Pop3CommandException ex) {
						Console.WriteLine ("Error downloading message {0}: {1}", i, ex.Message);
						Console.WriteLine ("\tStatusText: {0}", ex.StatusText);
						continue;
					} catch (Pop3ProtocolException ex) {
						Console.WriteLine ("Protocol error while sending message {0}: {1}", i, ex.Message);
						// most likely the connection has been dropped
						if (!client.IsConnected)
							break;
					}
				}

				if (client.IsConnected) {
					// if we do not disconnect cleanly, then the messages won't actually get deleted
					client.Disconnect (true);
				}
			}
		}
Пример #12
0
		public static void DownloadNewMessages (HashSet<string> previouslyDownloadedUids)
		{
			using (var client = new Pop3Client ()) {
				client.Connect ("pop.gmail.com", 995, SecureSocketOptions.SslOnConnect);

				client.Authenticate ("username", "password");

				if (!client.Capabilities.HasFlag (Pop3Capabilities.UIDL))
					throw new Exception ("The POP3 server does not support UIDs!");

				var uids = client.GetMessageUids ();

				for (int i = 0; i < client.Count; i++) {
					// check that we haven't already downloaded this message
					// in a previous session
					if (previouslyDownloadedUids.Contains (uids[i]))
						continue;

					var message = client.GetMessage (i);

					// write the message to a file
					message.WriteTo (string.Format ("{0}.msg", uids[i]));

					// add the message uid to our list of downloaded uids
					previouslyDownloadedUids.Add (uids[i]);
				}

				client.Disconnect (true);
			}
		}
Пример #13
0
		public static void DownloadMessages ()
		{
			using (var client = new Pop3Client ()) {
				client.Connect ("pop.gmail.com", 995, SecureSocketOptions.SslOnConnect);

				client.Authenticate ("username", "password");

				var messages = client.DownloadMessages (0, count);

				foreach (var message in messages) {
					// write the message to a file
					message.WriteTo (string.Format ("{0}.msg", i));
				}

				client.DeleteMessages (0, count);

				client.Disconnect (true);
			}
		}
Пример #14
0
        public List <REMail> ReadEMails()
        {
            bool NeedSave = false;

            try
            {
                using (readClient = new Pop3Client())
                {
                    var Server      = "mail.ccaserve.org";
                    var Port        = "110";
                    var UseSsl      = false;
                    var credentials = new NetworkCredential(fromAdr, fromPass);
                    var cancel      = new CancellationTokenSource();
                    var uri         = new Uri(string.Format("pop{0}://{1}:{2}", (UseSsl ? "s" : ""), Server, Port));

                    //Connect to email server
                    readClient.Connect(uri, cancel.Token);
                    readClient.AuthenticationMechanisms.Remove("XOAUTH2");
                    readClient.Authenticate(credentials, cancel.Token);

                    // Read EMails roughly after those we read last
                    var reList          = new List <REMail>();
                    var LatestEMailRead = _settings.LastEMailRead;
                    for (int i = 0; i < readClient.Count; i++)
                    {
                        var msg = readClient.GetMessage(i);

                        // Get Received Date and use it to keep track of emails we have already read and processed.
                        DateTime EMailReceived = default;
                        if (msg.Headers != null)
                        {
                            if (msg.Headers["Received"] != null)
                            {
                                var rval    = msg.Headers["Received"];
                                var rFields = rval.Split(";");
                                foreach (var f in rFields)
                                {
                                    var fld = f.Trim();
                                    if (fld.Length < 45)
                                    {
                                        EMailReceived = CSEMail.ParseDetailedDate(fld);
                                        if (EMailReceived != default)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        // Get DateTime Originally Sent

                        if ((EMailReceived == default) || (EMailReceived <= LatestEMailRead))
                        {
                            continue; // Either an Admin Delivery failure alert or already read. TBD : Case where multiple emails read the same second but on or more not proccessed.
                        }
                        var re = new REMail(i);
                        re.Subject  = msg.Subject;
                        re.HtmlBody = msg.HtmlBody;
                        re.TextBody = msg.TextBody;
                        var tbFlds = msg.TextBody.Split("\r\n");
                        foreach (var t in tbFlds)
                        {
                            var tfld = t.Trim();
                            if (tfld.StartsWith("Sent:") || tfld.StartsWith("Date:"))
                            {
                                re.Date = CSEMail.ParseDetailedDate(tfld);
                            }
                        }
                        re.From = (msg.Sender != null) ? msg.Sender.ToString() : (((msg.From != null) && (msg.From.Count > 0)) ? msg.From[0].ToString() : "unknown");
                        if (re.Date == default)
                        {
                            re.Date = PropMgr.UTCtoEST(msg.Date.DateTime);
                        }
                        re.Attachments = new List <string>();
                        foreach (var attachment in msg.Attachments)
                        {
                            var fileName = attachment.ContentDisposition?.FileName ?? attachment.ContentType.Name ?? "Att";
                            fileName = re.GetUniqueTempFileName(fileName, true);
                            using (var stream = File.Create(fileName))
                            {
                                if (attachment is MessagePart)
                                {
                                    var part = (MessagePart)attachment;

                                    part.Message.WriteTo(stream);
                                }
                                else
                                {
                                    var part = (MimePart)attachment;

                                    part.Content.DecodeTo(stream);
                                }
                            }
                            re.Attachments.Add(fileName);
                        }

                        // Sometimes images are in BodyParts. filter out other content
                        foreach (var attachment in msg.BodyParts)
                        {
                            var fileName = attachment.ContentDisposition?.FileName ?? attachment.ContentType.Name ?? "";
                            if (string.IsNullOrEmpty(fileName))
                            {
                                continue; // filter out other non-file content
                            }
                            fileName = re.GetUniqueTempFileName(fileName, true);
                            using (var stream = File.Create(fileName))
                            {
                                if (attachment is MessagePart)
                                {
                                    var part = (MessagePart)attachment;

                                    part.Message.WriteTo(stream);
                                }
                                else
                                {
                                    var part = (MimePart)attachment;

                                    part.Content.DecodeTo(stream);
                                }
                            }
                            re.Attachments.Add(fileName);
                        }


                        if (EMailReceived > _settings.LastEMailRead)
                        {
                            NeedSave = true;
                            _settings.LastEMailRead = EMailReceived;
                        }
                        reList.Add(re);
                    }
                    readClient.Disconnect(true);

                    if (NeedSave)
                    {
                        _settings.Save();
                    }

                    return(reList);
                }
            }
            catch (Exception e)
            {
                _ = e;
                return(new List <REMail>()); // TBD Log failure
            }
        }