コード例 #1
0
ファイル: Pop3ClientTests.cs プロジェクト: dcga/MailKit
		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
        /*
         * 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);
                }
            }
        }
コード例 #3
0
ファイル: MailReciever.cs プロジェクト: devmankz/Depmon
        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;
        }
コード例 #4
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;
            }
        }
コード例 #5
0
ファイル: Pop3Examples.cs プロジェクト: Gekctek/MailKit
		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);
			}
		}
コード例 #6
0
ファイル: Pop3Examples.cs プロジェクト: Gekctek/MailKit
		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);
			}
		}
コード例 #7
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;
            }
        }
コード例 #8
0
ファイル: Pop3Examples.cs プロジェクト: Gekctek/MailKit
		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);
				}
			}
		}
コード例 #9
0
ファイル: Pop3Examples.cs プロジェクト: Gekctek/MailKit
		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);
			}
		}
コード例 #10
0
ファイル: Pop3Examples.cs プロジェクト: Gekctek/MailKit
		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);
			}
		}
コード例 #11
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
            }
        }