Пример #1
0
		public void TestArgumentExceptions ()
		{
			using (var client = new Pop3Client ()) {
				var socket = new Socket (SocketType.Stream, ProtocolType.Tcp);

				// Connect
				Assert.Throws<ArgumentNullException> (() => client.Connect ((Uri) null));
				Assert.Throws<ArgumentNullException> (async () => await client.ConnectAsync ((Uri) null));
				Assert.Throws<ArgumentNullException> (() => client.Connect (null, 110, false));
				Assert.Throws<ArgumentNullException> (async () => await client.ConnectAsync (null, 110, false));
				Assert.Throws<ArgumentException> (() => client.Connect (string.Empty, 110, false));
				Assert.Throws<ArgumentException> (async () => await client.ConnectAsync (string.Empty, 110, false));
				Assert.Throws<ArgumentOutOfRangeException> (() => client.Connect ("host", -1, false));
				Assert.Throws<ArgumentOutOfRangeException> (async () => await client.ConnectAsync ("host", -1, false));
				Assert.Throws<ArgumentNullException> (() => client.Connect (null, 110, SecureSocketOptions.None));
				Assert.Throws<ArgumentNullException> (async () => await client.ConnectAsync (null, 110, SecureSocketOptions.None));
				Assert.Throws<ArgumentException> (() => client.Connect (string.Empty, 110, SecureSocketOptions.None));
				Assert.Throws<ArgumentException> (async () => await client.ConnectAsync (string.Empty, 110, SecureSocketOptions.None));
				Assert.Throws<ArgumentOutOfRangeException> (() => client.Connect ("host", -1, SecureSocketOptions.None));
				Assert.Throws<ArgumentOutOfRangeException> (async () => await client.ConnectAsync ("host", -1, SecureSocketOptions.None));

				Assert.Throws<ArgumentNullException> (() => client.Connect (null, "host", 110, SecureSocketOptions.None));
				Assert.Throws<ArgumentException> (() => client.Connect (socket, "host", 110, SecureSocketOptions.None));

				// Authenticate
				Assert.Throws<ArgumentNullException> (() => client.Authenticate (null));
				Assert.Throws<ArgumentNullException> (async () => await client.AuthenticateAsync (null));
				Assert.Throws<ArgumentNullException> (() => client.Authenticate (null, "password"));
				Assert.Throws<ArgumentNullException> (async () => await client.AuthenticateAsync (null, "password"));
				Assert.Throws<ArgumentNullException> (() => client.Authenticate ("username", null));
				Assert.Throws<ArgumentNullException> (async () => await client.AuthenticateAsync ("username", null));
			}
		}
Пример #2
0
		public void TestBasicPop3Client ()
		{
			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, 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);
				} 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);

				Assert.AreEqual (1, client.Count, "Expected 1 message");

				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");
			}
		}
Пример #3
0
        public MailClient(MailBox mailbox, CancellationToken cancelToken, int tcpTimeout = 30000,
                          bool certificatePermit = false, string protocolLogPath = "",
                          ILogger log            = null, bool skipSmtp = false)
        {
            var protocolLogger = !string.IsNullOrEmpty(protocolLogPath)
                ? (IProtocolLogger)
                                 new ProtocolLogger(protocolLogPath)
                : new NullProtocolLogger();

            Account = mailbox;
            Log     = log ?? new NullLogger();

            StopTokenSource = new CancellationTokenSource();

            CancelToken = CancellationTokenSource.CreateLinkedTokenSource(cancelToken, StopTokenSource.Token).Token;

            if (Account.Imap)
            {
                Imap = new ImapClient(protocolLogger)
                {
                    ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
                                                          certificatePermit ||
                                                          MailService.DefaultServerCertificateValidationCallback(sender, certificate, chain, errors),
                    Timeout = tcpTimeout
                };

                Pop = null;
            }
            else
            {
                Pop = new Pop3Client(protocolLogger)
                {
                    ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
                                                          certificatePermit ||
                                                          MailService.DefaultServerCertificateValidationCallback(sender, certificate, chain, errors),
                    Timeout = tcpTimeout
                };
                Imap = null;
            }

            if (skipSmtp)
            {
                Smtp = null;
                return;
            }

            Smtp = new SmtpClient(protocolLogger)
            {
                ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
                                                      certificatePermit ||
                                                      MailService.DefaultServerCertificateValidationCallback(sender, certificate, chain, errors),
                Timeout = tcpTimeout
            };
        }
Пример #4
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;
        }
Пример #5
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);
                }
            }
        }
Пример #6
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;
            }
        }
        public MailClient(MailBox mailbox, CancellationToken cancelToken, int tcpTimeout = 30000, bool certificatePermit = false,
                          ILogger log = null)
        {
            Account = mailbox;
            Log     = log ?? new NullLogger();

            StopTokenSource = new CancellationTokenSource();

            CancelToken = CancellationTokenSource.CreateLinkedTokenSource(cancelToken, StopTokenSource.Token).Token;

            if (Account.Imap)
            {
                Imap = new ImapClient
                {
                    ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
                                                          certificatePermit ||
                                                          MailService.DefaultServerCertificateValidationCallback(sender, certificate, chain, errors),
                    Timeout = tcpTimeout
                };

                Pop = null;
            }
            else
            {
                Pop = new Pop3Client
                {
                    ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
                                                          certificatePermit ||
                                                          MailService.DefaultServerCertificateValidationCallback(sender, certificate, chain, errors),
                    Timeout = tcpTimeout
                };
                Imap = null;
            }

            Smtp = new SmtpClient
            {
                ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
                                                      certificatePermit ||
                                                      MailService.DefaultServerCertificateValidationCallback(sender, certificate, chain, errors),
                Timeout = tcpTimeout
            };
        }
Пример #8
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);
			}
		}
Пример #9
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);
			}
		}
Пример #10
0
        /*
         * retrieves messages from pop3 server
         */
        private static void RetrieveMessagesFromServer(
            Node pars,
            Node dp,
            Node ip,
            string basePath,
            string attachmentDirectory,
            string linkedAttachmentDirectory,
            Node exeNode,
            Pop3Client client)
        {
            int serverCount = client.GetMessageCount();
            int count = Expressions.GetExpressionValue<int>(ip.GetValue("count", serverCount.ToString()), dp, ip, false);
            count = Math.Min(serverCount, count);

            bool delete = Expressions.GetExpressionValue<bool>(ip.GetValue("delete", "false"), dp, ip, false);

            for (int idxMsg = 0; idxMsg < count; idxMsg++)
            {
                MimeMessage msg = client.GetMessage(idxMsg);
                HandleMessage(
                    pars,
                    ip,
                    basePath,
                    attachmentDirectory,
                    linkedAttachmentDirectory,
                    exeNode,
                    idxMsg,
                    msg);

                if (delete)
                    client.DeleteMessage(idxMsg);
            }
        }
Пример #11
0
		public async void TestLangExtension ()
		{
			var commands = new List<Pop3ReplayCommand> ();
			commands.Add (new Pop3ReplayCommand ("", "lang.greeting.txt"));
			commands.Add (new Pop3ReplayCommand ("CAPA\r\n", "lang.capa1.txt"));
			commands.Add (new Pop3ReplayCommand ("UTF8\r\n", "lang.utf8.txt"));
			commands.Add (new Pop3ReplayCommand ("APOP username d99894e8445daf54c4ce781ef21331b7\r\n", "lang.auth.txt"));
			commands.Add (new Pop3ReplayCommand ("CAPA\r\n", "lang.capa2.txt"));
			commands.Add (new Pop3ReplayCommand ("STAT\r\n", "lang.stat.txt"));
			commands.Add (new Pop3ReplayCommand ("LANG\r\n", "lang.getlang.txt"));
			commands.Add (new Pop3ReplayCommand ("LANG en\r\n", "lang.setlang.txt"));
			commands.Add (new Pop3ReplayCommand ("QUIT\r\n", "gmail.quit.txt"));

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

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

				Assert.AreEqual (LangCapa1, 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");

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

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

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

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

				Assert.AreEqual (3, client.Count, "Expected 3 messages");

				var languages = await client.GetLanguagesAsync ();
				Assert.AreEqual (6, languages.Count);
				Assert.AreEqual ("en", languages[0].Language);
				Assert.AreEqual ("English", languages[0].Description);
				Assert.AreEqual ("en-boont", languages[1].Language);
				Assert.AreEqual ("English Boontling dialect", languages[1].Description);
				Assert.AreEqual ("de", languages[2].Language);
				Assert.AreEqual ("Deutsch", languages[2].Description);
				Assert.AreEqual ("it", languages[3].Language);
				Assert.AreEqual ("Italiano", languages[3].Description);
				Assert.AreEqual ("es", languages[4].Language);
				Assert.AreEqual ("Espanol", languages[4].Description);
				Assert.AreEqual ("sv", languages[5].Language);
				Assert.AreEqual ("Svenska", languages[5].Description);

				await client.SetLanguageAsync ("en");

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

				Assert.IsFalse (client.IsConnected, "Failed to disconnect");
			}
		}
Пример #12
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;
            }
        }
Пример #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
        /*
         * retrieves messages from pop3 server
         */
        private static void RetrieveMessagesFromServer(
            Node pars, 
            Node dp,
            Node ip, 
            string basePath, 
            string attachmentDirectory, 
            string linkedAttachmentDirectory, 
            Node exeNode, 
            Pop3Client client)
        {
            int serverCount = client.GetMessageCount();
            int count = Expressions.GetExpressionValue<int>(ip.GetValue("count", serverCount.ToString()), dp, ip, false);
            count = Math.Min(serverCount, count);

            bool delete = Expressions.GetExpressionValue<bool>(ip.GetValue("delete", "false"), dp, ip, false);

            for (int idxMsg = 0; idxMsg < count; idxMsg++)
            {
                // short circuting in case message is already downloaded
                string uuid = null;
                if (client.SupportsUids)
                {
                    uuid = client.GetMessageUid(idxMsg);
                    if (MessageAlreadyDownloaded(uuid))
                        continue;
                }

                MimeMessage msg = client.GetMessage(idxMsg);
                HandleMessage(
                    pars,
                    ip,
                    basePath,
                    attachmentDirectory,
                    linkedAttachmentDirectory,
                    exeNode,
                    idxMsg,
                    msg,
                    uuid);

                if (delete)
                    client.DeleteMessage(idxMsg);
            }
        }
Пример #15
0
		public async 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 ("RETR 1\r\nRETR 2\r\nRETR 3\r\n", "gmail.retr123.txt"));
			commands.Add (new Pop3ReplayCommand ("QUIT\r\n", "gmail.quit.txt"));

			using (var client = new Pop3Client ()) {
				try {
					client.ReplayConnect ("localhost", new Pop3ReplayStream (commands, false));
				} 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 {
					await client.AuthenticateAsync ("username", "password");
				} 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);

				Assert.AreEqual (3, client.Count, "Expected 3 messages");

				try {
					var message = await client.GetMessageAsync (0);

					using (var jpeg = new MemoryStream ()) {
						var attachment = message.Attachments.OfType<MimePart> ().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 {
					var messages = await client.GetMessagesAsync (new [] { 0, 1, 2 });

					foreach (var message in messages) {
						using (var jpeg = new MemoryStream ()) {
							var attachment = message.Attachments.OfType<MimePart> ().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 GetMessages: {0}", ex);
				}

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

				Assert.IsFalse (client.IsConnected, "Failed to disconnect");
			}
		}
Пример #16
0
		public async 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 ("UIDL\r\n", "gmail.uidl.txt"));
			commands.Add (new Pop3ReplayCommand ("UIDL 1\r\n", "gmail.uidl1.txt"));
			commands.Add (new Pop3ReplayCommand ("UIDL 2\r\n", "gmail.uidl2.txt"));
			commands.Add (new Pop3ReplayCommand ("UIDL 3\r\n", "gmail.uidl3.txt"));
			commands.Add (new Pop3ReplayCommand ("LIST\r\n", "gmail.list.txt"));
			commands.Add (new Pop3ReplayCommand ("LIST 1\r\n", "gmail.list1.txt"));
			commands.Add (new Pop3ReplayCommand ("LIST 2\r\n", "gmail.list2.txt"));
			commands.Add (new Pop3ReplayCommand ("LIST 3\r\n", "gmail.list3.txt"));
			commands.Add (new Pop3ReplayCommand ("RETR 1\r\n", "gmail.retr1.txt"));
			commands.Add (new Pop3ReplayCommand ("RETR 1\r\nRETR 2\r\nRETR 3\r\n", "gmail.retr123.txt"));
			commands.Add (new Pop3ReplayCommand ("RETR 1\r\nRETR 2\r\nRETR 3\r\n", "gmail.retr123.txt"));
			commands.Add (new Pop3ReplayCommand ("TOP 1 0\r\n", "gmail.top.txt"));
			commands.Add (new Pop3ReplayCommand ("TOP 1 0\r\nTOP 2 0\r\nTOP 3 0\r\n", "gmail.top123.txt"));
			commands.Add (new Pop3ReplayCommand ("TOP 1 0\r\nTOP 2 0\r\nTOP 3 0\r\n", "gmail.top123.txt"));
			commands.Add (new Pop3ReplayCommand ("RETR 1\r\n", "gmail.retr1.txt"));
			commands.Add (new Pop3ReplayCommand ("RETR 1\r\nRETR 2\r\nRETR 3\r\n", "gmail.retr123.txt"));
			commands.Add (new Pop3ReplayCommand ("RETR 1\r\nRETR 2\r\nRETR 3\r\n", "gmail.retr123.txt"));
			commands.Add (new Pop3ReplayCommand ("NOOP\r\n", "gmail.noop.txt"));
			commands.Add (new Pop3ReplayCommand ("DELE 1\r\n", "gmail.dele.txt"));
			commands.Add (new Pop3ReplayCommand ("RSET\r\n", "gmail.rset.txt"));
			commands.Add (new Pop3ReplayCommand ("DELE 1\r\nDELE 2\r\nDELE 3\r\n", "gmail.dele123.txt"));
			commands.Add (new Pop3ReplayCommand ("RSET\r\n", "gmail.rset.txt"));
			commands.Add (new Pop3ReplayCommand ("DELE 1\r\nDELE 2\r\nDELE 3\r\n", "gmail.dele123.txt"));
			commands.Add (new Pop3ReplayCommand ("RSET\r\n", "gmail.rset.txt"));
			commands.Add (new Pop3ReplayCommand ("DELE 1\r\nDELE 2\r\nDELE 3\r\n", "gmail.dele123.txt"));
			commands.Add (new Pop3ReplayCommand ("RSET\r\n", "gmail.rset.txt"));
			commands.Add (new Pop3ReplayCommand ("QUIT\r\n", "gmail.quit.txt"));

			using (var client = new Pop3Client ()) {
				try {
					client.ReplayConnect ("localhost", new Pop3ReplayStream (commands, false));
				} 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 {
					await client.AuthenticateAsync ("username", "password");
				} 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);

				Assert.AreEqual (3, client.Count, "Expected 3 messages");

				var uids = await client.GetMessageUidsAsync ();
				Assert.AreEqual (3, uids.Count);
				Assert.AreEqual ("101", uids[0]);
				Assert.AreEqual ("102", uids[1]);
				Assert.AreEqual ("103", uids[2]);

				for (int i = 0; i < 3; i++) {
					var uid = await client.GetMessageUidAsync (i);

					Assert.AreEqual (uids[i], uid);
				}

				var sizes = await client.GetMessageSizesAsync ();
				Assert.AreEqual (3, sizes.Count);
				Assert.AreEqual (1024, sizes[0]);
				Assert.AreEqual (1025, sizes[1]);
				Assert.AreEqual (1026, sizes[2]);

				for (int i = 0; i < 3; i++) {
					var size = await client.GetMessageSizeAsync (i);

					Assert.AreEqual (sizes[i], size);
				}

				try {
					var message = await client.GetMessageAsync (0);

					using (var jpeg = new MemoryStream ()) {
						var attachment = message.Attachments.OfType<MimePart> ().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 {
					var messages = await client.GetMessagesAsync (0, 3);

					foreach (var message in messages) {
						using (var jpeg = new MemoryStream ()) {
							var attachment = message.Attachments.OfType<MimePart> ().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 GetMessages: {0}", ex);
				}

				try {
					var messages = await client.GetMessagesAsync (new [] { 0, 1, 2 });

					foreach (var message in messages) {
						using (var jpeg = new MemoryStream ()) {
							var attachment = message.Attachments.OfType<MimePart> ().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 GetMessages: {0}", ex);
				}

				try {
					var header = await client.GetMessageHeadersAsync (0);

					Assert.AreEqual ("Test inline image", header[HeaderId.Subject]);
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in GetMessageHeaders: {0}", ex);
				}

				try {
					var headers = await client.GetMessageHeadersAsync (0, 3);

					Assert.AreEqual (3, headers.Count);
					for (int i = 0; i < headers.Count; i++)
						Assert.AreEqual ("Test inline image", headers[i][HeaderId.Subject]);
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in GetMessageHeaders: {0}", ex);
				}

				try {
					var headers = await client.GetMessageHeadersAsync (new [] { 0, 1, 2 });

					Assert.AreEqual (3, headers.Count);
					for (int i = 0; i < headers.Count; i++)
						Assert.AreEqual ("Test inline image", headers[i][HeaderId.Subject]);
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in GetMessageHeaders: {0}", ex);
				}

				try {
					using (var stream = await client.GetStreamAsync (0)) {
					}
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in GetStream: {0}", ex);
				}

				try {
					var streams = await client.GetStreamsAsync (0, 3);

					Assert.AreEqual (3, streams.Count);
					for (int i = 0; i < 3; i++) {
						streams[i].Dispose ();
					}
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in GetStreams: {0}", ex);
				}

				try {
					var streams = await client.GetStreamsAsync (new int[] { 0, 1, 2 });

					Assert.AreEqual (3, streams.Count);
					for (int i = 0; i < 3; i++) {
						streams[i].Dispose ();
					}
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in GetStreams: {0}", ex);
				}

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

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

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

				try {
					await client.DeleteMessagesAsync (new [] { 0, 1, 2 });
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in DeleteMessages: {0}", ex);
				}

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

				try {
					await client.DeleteMessagesAsync (0, 3);
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in DeleteMessages: {0}", ex);
				}

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

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

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

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

				Assert.IsFalse (client.IsConnected, "Failed to disconnect");
			}
		}
Пример #17
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");
            }
        }
Пример #18
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);
			}
		}
Пример #19
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);
				}
			}
		}
Пример #20
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");
            }
        }
Пример #21
0
		public async void TestInvalidStateExceptions ()
		{
			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 ()) {
				Assert.Throws<ServiceNotConnectedException> (async () => await client.AuthenticateAsync ("username", "password"));
				Assert.Throws<ServiceNotConnectedException> (async () => await client.AuthenticateAsync (new NetworkCredential ("username", "password")));

				Assert.Throws<ServiceNotConnectedException> (async () => await client.NoOpAsync ());

				Assert.Throws<ServiceNotConnectedException> (async () => await client.GetMessageSizesAsync ());
				Assert.Throws<ServiceNotConnectedException> (async () => await client.GetMessageSizeAsync ("uid"));
				Assert.Throws<ServiceNotConnectedException> (async () => await client.GetMessageSizeAsync (0));
				Assert.Throws<ServiceNotConnectedException> (async () => await client.GetMessageUidsAsync ());
				Assert.Throws<ServiceNotConnectedException> (async () => await client.GetMessageUidAsync (0));
				Assert.Throws<ServiceNotConnectedException> (async () => await client.GetMessageAsync ("uid"));
				Assert.Throws<ServiceNotConnectedException> (async () => await client.GetMessageAsync (0));
				Assert.Throws<ServiceNotConnectedException> (async () => await client.GetMessageHeadersAsync ("uid"));
				Assert.Throws<ServiceNotConnectedException> (async () => await client.GetMessageHeadersAsync (0));
				Assert.Throws<ServiceNotConnectedException> (async () => await client.GetStreamAsync (0));
				Assert.Throws<ServiceNotConnectedException> (async () => await client.GetStreamsAsync (0, 1));
				Assert.Throws<ServiceNotConnectedException> (async () => await client.GetStreamsAsync (new int[] { 0 }));
				Assert.Throws<ServiceNotConnectedException> (async () => await client.DeleteMessageAsync ("uid"));
				Assert.Throws<ServiceNotConnectedException> (async () => await client.DeleteMessageAsync (0));

				try {
					client.ReplayConnect ("localhost", new Pop3ReplayStream (commands, false));
				} 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);

				Assert.Throws<AuthenticationException> (async () => await client.AuthenticateAsync ("username", "password"));
				Assert.IsTrue (client.IsConnected, "AuthenticationException should not cause a disconnect.");

				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.GetMessageSizesAsync ());
				Assert.IsTrue (client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect.");

				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.GetMessageSizeAsync ("uid"));
				Assert.IsTrue (client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect.");

				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.GetMessageSizeAsync (0));
				Assert.IsTrue (client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect.");

				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.GetMessageUidsAsync ());
				Assert.IsTrue (client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect.");

				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.GetMessageUidAsync (0));
				Assert.IsTrue (client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect.");

				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.GetMessageAsync ("uid"));
				Assert.IsTrue (client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect.");

				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.GetMessageAsync (0));
				Assert.IsTrue (client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect.");

				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.GetMessageHeadersAsync ("uid"));
				Assert.IsTrue (client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect.");

				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.GetMessageHeadersAsync (0));
				Assert.IsTrue (client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect.");

				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.GetStreamAsync (0));
				Assert.IsTrue (client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect.");

				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.GetStreamsAsync (0, 1));
				Assert.IsTrue (client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect.");

				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.GetStreamsAsync (new int[] { 0 }));
				Assert.IsTrue (client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect.");

				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.DeleteMessageAsync ("uid"));
				Assert.IsTrue (client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect.");

				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.DeleteMessageAsync (0));
				Assert.IsTrue (client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect.");

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

				Assert.IsFalse (client.IsConnected, "Failed to disconnect");
			}
		}
Пример #22
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");
            }
        }
Пример #23
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
            }
        }