예제 #1
0
        public virtual MailMessage GetMessage(string uid, bool headersOnly = false)
        {
            CheckConnectionStatus();
            var line = SendCommandGetResponse(string.Format(headersOnly ? "TOP {0} 0" : "RETR {0}", uid));
            var size = rxOctets.Match(line).Groups[1].Value.ToInt();

            CheckResultOK(line);
            var msg = new MailMessage();

            msg.Load(_Stream, headersOnly, size, '.');

            msg.Uid = uid;
            var last = GetResponse();

            if (string.IsNullOrEmpty(last))
            {
                last = GetResponse();
            }

            if (last != ".")
            {
                System.Diagnostics.Debugger.Break();
                RaiseWarning(msg, "Expected \".\" in stream, but received \"" + last + "\"");
            }

            return(msg);
        }
예제 #2
0
        public virtual void GetMessages(string start, string end, bool uid, bool uidsonly, bool headersonly, bool setseen, Action <MailMessage> processCallback)
        {
            GetMessages(start, end, uid, uidsonly, headersonly, setseen, (stream, size, imapHeaders) =>
            {
                var mail = new MailMessage {
                    Encoding = Encoding
                };
                mail.Size = size;

                if (imapHeaders["UID"] != null)
                {
                    mail.Uid = imapHeaders["UID"];
                }

                if (imapHeaders["Flags"] != null)
                {
                    mail.SetFlags(imapHeaders["Flags"]);
                }

                mail.Load(_Stream, headersonly, mail.Size);

                foreach (var key in imapHeaders.AllKeys.Except(new[] { "UID", "Flags", "BODY[]", "BODY[HEADER]" }, StringComparer.OrdinalIgnoreCase))
                {
                    mail.Headers.Add(key, new HeaderValue(imapHeaders[key]));
                }

                processCallback?.Invoke(mail);

                return(mail);
            });
        }
예제 #3
0
        public virtual MailMessage[] GetMessages(string start, string end, bool uid, bool headersonly, bool setseen)
        {
            var x = new List <MailMessage>();

            GetMessages(start, end, uid, headersonly, setseen, (stream, size, imapHeaders) => {
                var mail = new MailMessage {
                    Encoding = Encoding
                };
                mail.Size = size;

                if (imapHeaders["UID"] != null)
                {
                    mail.Uid = imapHeaders["UID"];
                }

                if (imapHeaders["Flags"] != null)
                {
                    mail.SetFlags(imapHeaders["Flags"]);
                }

                mail.Load(_Stream, headersonly, mail.Size);

                foreach (var key in imapHeaders.AllKeys.Except(new[] { "UID", "Flags", "BODY[]", "BODY[HEADER]" }, StringComparer.OrdinalIgnoreCase))
                {
                    mail.Headers.Add(key, new HeaderValue(imapHeaders[key]));
                }

                x.Add(mail);

                return(mail);
            });

            return(x.ToArray());
        }
예제 #4
0
파일: UnitTest1.cs 프로젝트: ewrpi/HomeApps
        private AE.Net.Mail.MailMessage GetMessage(string raw)
        {
            var msg = new AE.Net.Mail.MailMessage();

            msg.Load(raw, false);

            return(msg);
        }
예제 #5
0
        public MailMessage GetMessage(string uid, bool headersOnly = false)
        {
            CheckConnectionStatus();
              var result = new StringBuilder();
              string line = SendCommandGetResponse(string.Format(headersOnly ? "TOP {0} 0" : "RETR {0}", uid));
              var size = rxOctets.Match(line).Groups[1].Value.ToInt();

              var msg = new MailMessage();
              msg.Load(_Stream, headersOnly, size);
              msg.Uid = uid;
              var last = GetResponse();
              System.Diagnostics.Debug.Assert(last == ".");
              return msg;
        }
예제 #6
0
        public MailMessage GetMessage(string uid, bool headersOnly = false) {
            CheckConnectionStatus();
            var result = new StringBuilder();
            string line = SendCommandGetResponse(string.Format(headersOnly ? "TOP {0} 0" : "RETR {0}", uid));
            while (line != ".") {
                result.AppendLine(line);
                line = GetResponse();
            }

            var msg = new MailMessage();
            msg.Load(result.ToString(), headersOnly);
            msg.Uid = uid;
            return msg;
        }
예제 #7
0
        public MailMessage GetMessage(string uid, bool headersOnly = false)
        {
            CheckConnectionStatus();
            var    result = new StringBuilder();
            string line   = SendCommandGetResponse(string.Format(headersOnly ? "TOP {0} 0" : "RETR {0}", uid));

            while (line != ".")
            {
                result.AppendLine(line);
                line = GetResponse();
            }

            var msg = new MailMessage();

            msg.Load(result.ToString(), headersOnly);
            msg.Uid = uid;
            return(msg);
        }
예제 #8
0
파일: Clients.cs 프로젝트: kasumu/aenetmail
        public void Download_Message()
        {
            var filename = System.IO.Path.GetTempFileName();

            try {
                using (var imap = GetClient <ImapClient>())
                    using (var file = new System.IO.FileStream(filename, System.IO.FileMode.Create)) {
                        imap.DownloadMessage(file, 0, false);
                    }

                using (var file = new System.IO.FileStream(filename, System.IO.FileMode.Open)) {
                    var msg = new AE.Net.Mail.MailMessage();
                    msg.Load(file);
                    msg.Subject.ShouldNotBeNullOrEmpty();
                }
            } finally {
                System.IO.File.Delete(filename);
            }
        }
예제 #9
0
		public void Parse_Spam() {
			var dir = System.IO.Path.Combine(Environment.CurrentDirectory.Split(new[] { "AE.Net.Mail" }, StringSplitOptions.RemoveEmptyEntries)[0],
				"AE.Net.Mail\\Tests\\Spam");
			var files = System.IO.Directory.GetFiles(dir, "*.lorien", System.IO.SearchOption.AllDirectories);

			var mindate = new DateTime(1900, 1, 1).Ticks;
			var maxdate = DateTime.MaxValue.Ticks;
			var rxSubject = new Regex(@"^Subject\:\s+\S+");
			MailMessage msg = new MailMessage();
			for (var i = 0; i < files.Length; i++) {
				var file = files[i];
				var txt = System.IO.File.ReadAllText(file);
				using (var stream = System.IO.File.OpenRead(file))
					msg.Load(stream, false, (int)stream.Length);

				if (msg.ContentTransferEncoding.IndexOf("quoted", StringComparison.OrdinalIgnoreCase) == -1) {
					continue;
				}

				if (string.IsNullOrEmpty(msg.Body)) {
					continue;
				}

				try {

					msg.Date.Ticks.Should().Be.InRange(mindate, maxdate);
					if (string.IsNullOrEmpty(msg.Subject) && rxSubject.IsMatch(txt))
						throw new AssertFailedException("subject is null or empty");
					//msg.From.Should().Not.Be.Null();
					if (msg.To.Count > 0) msg.To.First().Should().Not.Be.Null();
					if (msg.Cc.Count > 0) msg.Cc.First().Should().Not.Be.Null();
					if (msg.Bcc.Count > 0) msg.Bcc.First().Should().Not.Be.Null();

					(msg.Body ?? string.Empty).Trim().Should().Not.Be.NullOrEmpty();


				} catch (Exception ex) {
					Console.WriteLine(ex);
					Console.WriteLine(txt);
					throw;
				}
			}
		}
예제 #10
0
        public MailMessage GetMessage(string uid, bool headersOnly = false)
        {
            CheckConnectionStatus();
            var    result = new StringBuilder();
            string line   = SendCommandGetResponse(string.Format(headersOnly ? "TOP {0} 0" : "RETR {0}", uid));
            var    size   = rxOctets.Match(line).Groups[1].Value.ToInt();

            var msg = new MailMessage();

            msg.Load(_Stream, headersOnly, size);
            msg.Uid = uid;
            var last = GetResponse();

            if (last.StartsWith("-"))
            {
                last = GetResponse();
            }
            System.Diagnostics.Debug.Assert(last == ".");
            return(msg);
        }
예제 #11
0
        public virtual MailMessage GetMessage(string uid, bool headersOnly = false)
        {
            CheckConnectionStatus();
            var line = SendCommandGetResponse(string.Format(headersOnly ? "TOP {0} 0" : "RETR {0}", uid));
            var size = rxOctets.Match(line).Groups[1].Value.ToInt();
            CheckResultOK(line);
            var msg = new MailMessage();
            msg.Load(_Stream, headersOnly, size, '.');

            msg.Uid = uid;
            var last = GetResponse();
            if (string.IsNullOrEmpty(last))
                last = GetResponse();

            if (last != ".") {
                System.Diagnostics.Debugger.Break();
                RaiseWarning(msg, "Expected \".\" in stream, but received \"" + last + "\"");
            }

            return msg;
        }
예제 #12
0
        public void RecognizeBase64EncodedMail()
        {
            var msg = new MailMessage();
            msg.Load(@"Delivered-To: [email protected]
            Received: by 10.112.29.134 with SMTP id k6cs32313lbh;
            Wed, 8 Feb 2012 03:31:35 -0800 (PST)
            Received: by 10.213.13.218 with SMTP id d26mr2697709eba.56.1328700694648;
            Wed, 08 Feb 2012 03:31:34 -0800 (PST)
            Return-Path: <*****@*****.**>
            Received: from smtpout01.onlinespamfilter.nl (smtpout01.onlinespamfilter.nl. [217.21.240.157])
            by mx.google.com with ESMTPS id b46si798117eei.102.2012.02.08.03.31.34
            (version=TLSv1/SSLv3 cipher=OTHER);
            Wed, 08 Feb 2012 03:31:34 -0800 (PST)
            Received-SPF: neutral (google.com: 217.21.240.157 is neither permitted nor denied by best guess record for domain of [email protected]) client-ip=217.21.240.157;
            Authentication-Results: mx.google.com; spf=neutral (google.com: 217.21.240.157 is neither permitted nor denied by best guess record for domain of [email protected]) [email protected]
            Received: from smtp.onlinespamfilter.nl (localhost [127.0.0.1])
            by smtp.onlinespamfilter.nl (Postfix) with ESMTP id F29C025088
            for <*****@*****.**>; Wed,  8 Feb 2012 12:31:32 +0100 (CET)
            Received: from [77.62.58.8] (unknown [77.62.58.8])
            (using TLSv1 with cipher RC4-MD5 (128/128 bits))
            (No client certificate requested)
            by smtp.onlinespamfilter.nl (Postfix) with ESMTP
            for <*****@*****.**>; Wed,  8 Feb 2012 12:31:32 +0100 (CET)
            To: [email protected]
            From: #=?utf-8?B?QmFydCBTYW5kZXJz?=# <*****@*****.**>
            Subject:
            Date: Wed, 08 Feb 2012 12:31:22 +0100
            MIME-Version: 1.0
            Content-Type: multipart/alternative;
            boundary=#----=_Part_0_1328700682140#
            Message-ID: <*****@*****.**>
            X-OSF-Virus: CLEAN
            X-OSF-Outgoing: Innocent
            X-OSF-SUM: 97ab0211c2938cdf9afc5a79ac55dbc4
            X-OSF-Info: Checked for spam and viruses

            ------=_Part_0_1328700682140
            Content-Type: text/plain;
            charset=utf-8
            Content-Transfer-Encoding: base64
            Content-Disposition: inline

            aHR0cDovL3d3dy55b3V0dWJlLmNvbS93YXRjaD92PU56ZXVTNkJpV0M4CgoKCg==

            ------=_Part_0_1328700682140
            Content-Type: text/html;
            charset=utf-8
            Content-Transfer-Encoding: base64
            Content-Disposition: inline

            PGEgaHJlZj0iaHR0cDovL3d3dy55b3V0dWJlLmNvbS93YXRjaD92PU56ZXVTNkJpV0M4Ij5odHRw
            Oi8vd3d3LnlvdXR1YmUuY29tL3dhdGNoP3Y9TnpldVM2QmlXQzg8L2E+PGJyPjxicj48YnI+PGJy
            Pg==

            ------=_Part_0_1328700682140--".Replace("#", "\""));
            input.Publish(msg);

            Assert.AreEqual(1, sink.Messages.Count);
            var clip = sink.Messages[0];
            Assert.AreEqual("NzeuS6BiWC8", clip.ID);
        }
예제 #13
0
        public MailMessage[] GetMessages(string start, string end, bool uid, bool headersonly, bool setseen)
        {
            CheckMailboxSelected();
            IdlePause();

            string tag = GetTag();
            string command = tag + (uid ? "UID " : null)
              + "FETCH " + start + ":" + end + " ("
              + _FetchHeaders + "UID FLAGS BODY"
              + (setseen ? ".PEEK" : null)
              + "[" + (headersonly ? "HEADER" : null) + "])";

            string response;
            var x = new List<MailMessage>();

            SendCommand(command);
            while (true)
            {
                response = GetResponse();
                if (string.IsNullOrEmpty(response) || response.Contains(tag + "OK"))
                    break;

                if (response[0] != '*' || !response.Contains("FETCH ("))
                    continue;

                var mail = new MailMessage { Encoding = Encoding };
                var imapHeaders = ParseImapHeader(response.Substring(response.IndexOf('(') + 1));
                mail.Size = (imapHeaders["BODY[HEADER]"] ?? imapHeaders["BODY[]"]).Trim('{', '}').ToInt();

                if (imapHeaders["UID"] != null)
                    mail.Uid = imapHeaders["UID"];

                if (imapHeaders["Flags"] != null)
                    mail.SetFlags(imapHeaders["Flags"]);

                foreach (var key in imapHeaders.AllKeys.Except(new[] { "UID", "Flags", "BODY[]", "BODY[HEADER]" }, StringComparer.OrdinalIgnoreCase))
                    mail.Headers.Add(key, new HeaderValue(imapHeaders[key]));

                using (var body = new System.IO.MemoryStream())
                {
                    int remaining = mail.Size;
                    var buffer = new byte[8192];
                    int read;
                    string pattern = "charset=";
                    string charset = "";
                    string temp_charset = Encoding.BodyName;
                    while (remaining > 0)
                    {
                        read = _Stream.Read(buffer, 0, Math.Min(remaining, buffer.Length));
                        string temp_body = Encoding.GetString(buffer, 0, read);
                        temp_body = temp_body.Replace("\"", "").Replace(" ", "");
                        if (temp_body.ToLower().Contains(pattern))
                        {
                            int start_pos = temp_body.IndexOf(pattern) + pattern.Length;
                            int end_pos = temp_body.IndexOf("\r\n", start_pos);
                            if (end_pos == -1)
                            {
                                end_pos = temp_body.IndexOf("\r", start_pos);
                                if (end_pos == -1)
                                    end_pos = temp_body.IndexOf(";", start_pos);
                            }
                            if (end_pos != -1)
                            {
                                int length = end_pos - start_pos;
                                if (length > 0)
                                {
                                    charset = temp_body.Substring(start_pos, length).Replace(";", "");
                                    if (charset != "" && !charset.Contains("binaryname") && charset != temp_charset)
                                    {
                                        Encoding = Utilities.ParseCharsetToEncoding(charset, Encoding);
                                        temp_charset = Encoding.BodyName;
                                    }
                                }
                            }
                        }

                        body.Write(buffer, 0, read);
                        remaining -= read;
                    }

                    var next = Convert.ToChar(_Stream.ReadByte());
                    System.Diagnostics.Debug.Assert(next == ')');

                    body.Position = 0;
                    using (var rdr = new System.IO.StreamReader(body, Encoding))
                    {
                        mail.Load(rdr, headersonly);
                    }
                }

                x.Add(mail);
            }

            IdleResume();
            return x.ToArray();
        }
예제 #14
0
        public MailMessage[] GetMessages(string start, string end, bool uid, bool headersonly, bool setseen)
        {
            CheckMailboxSelected();
              IdlePause();

              string UID, HEADERS, SETSEEN;
              UID = HEADERS = SETSEEN = String.Empty;
              if (uid) UID = "UID ";
              if (headersonly) HEADERS = "HEADER";
              if (setseen) SETSEEN = ".PEEK";
              string tag = GetTag();
              string command = tag + UID + "FETCH " + start + ":" + end + " (UID RFC822.SIZE FLAGS BODY" + SETSEEN + "[" + HEADERS + "])";
              string response = SendCommandGetResponse(command);
              var x = new List<MailMessage>();
              string reg = @"\* \d+ FETCH.*?BODY.*?\{(\d+)\}";
              Match m = Regex.Match(response, reg);
              string bodies = String.Empty;
              while (m.Groups.Count > 1) {
            int bodyremaininglen = Convert.ToInt32(m.Groups[1].ToString());
            MailMessage mail = new MailMessage();
            //char[] body = new char[bodylen];
            string body = String.Empty;
            while (bodyremaininglen > 0) {
              bodies += GetResponse();
              if (bodyremaininglen < bodies.Length) {
            body += bodies.Substring(0, bodyremaininglen);
            bodyremaininglen = 0;
            bodies = bodies.Remove(0);
              } else {
            body += bodies + Environment.NewLine;
            bodyremaininglen -= bodies.Length + 2;  //extra 2 for CRLF
            bodies = "";
              }
            }

            Match m2 = Regex.Match(response, @"UID (\d+)");
            if (m2.Groups[1] != null) mail.Uid = m2.Groups[1].ToString();
            m2 = Regex.Match(response, @"FLAGS \((.*?)\)");
            if (m2.Groups[1] != null) mail.SetFlags(m2.Groups[1].ToString());
            m2 = Regex.Match(response, @"RFC822\.SIZE (\d+)");
            if (m2.Groups[1] != null) mail.Size = Convert.ToInt32(m2.Groups[1].ToString());
            mail.Load(body, headersonly);
            x.Add(mail);
            response = GetResponse(); // read last line terminated by )
            m = Regex.Match(response, reg);
              }

              IdleResume();
              return x.ToArray();
        }
예제 #15
0
        public MailMessage[] GetMessages(string start, string end, bool uid, bool headersonly, bool setseen)
        {
            CheckMailboxSelected();
            IdlePause();

            string tag     = GetTag();
            string command = tag + (uid ? "UID " : null)
                             + "FETCH " + start + ":" + end + " ("
                             + _FetchHeaders + "UID RFC822.SIZE FLAGS BODY"
                             + (setseen ? ".PEEK" : null)
                             + "[" + (headersonly ? "HEADER" : null) + "])";

            string response;
            var    x = new List <MailMessage>();

            SendCommand(command);
            while (true)
            {
                response = GetResponse();
                if (string.IsNullOrEmpty(response) || response.Contains(tag + "OK"))
                {
                    break;
                }

                if (response[0] != '*' || !response.Contains("FETCH ("))
                {
                    continue;
                }

                var mail        = new MailMessage();
                var imapHeaders = ParseImapHeader(response.Substring(response.IndexOf('(') + 1));
                if (imapHeaders["UID"] != null)
                {
                    mail.Uid = imapHeaders["UID"];
                }

                if (imapHeaders["Flags"] != null)
                {
                    mail.SetFlags(imapHeaders["Flags"]);
                }

                if (imapHeaders["RFC822.SIZE"] != null)
                {
                    mail.Size = imapHeaders["RFC822.SIZE"].ToInt();
                }

                foreach (var key in imapHeaders.AllKeys.Except(new[] { "UID", "Flags", "RFC822.SIZE", "BODY[]", "BODY[HEADER]" }, StringComparer.OrdinalIgnoreCase))
                {
                    mail.Headers.Add(key, new HeaderValue(imapHeaders[key]));
                }

                int bodySize = (imapHeaders["BODY[HEADER]"] ?? imapHeaders["BODY[]"]).Trim('{', '}').ToInt();

                int size   = Math.Min(bodySize, mail.Size > 0 ? mail.Size : bodySize);
                var body   = new StringBuilder();
                var buffer = new char[8192];
                int read;
                while (size > 0)
                {
                    read = _Reader.Read(buffer, 0, Math.Min(size, buffer.Length));
                    body.Append(buffer, 0, read);
                    size -= read;
                    if (size == 0)
                    {
                        if (_Reader.Peek() != ')')
                        {
                            size     = Math.Max(bodySize, mail.Size) - Math.Min(bodySize, mail.Size > 0 ? mail.Size : bodySize);
                            bodySize = Math.Max(bodySize, mail.Size);
                        }
                    }
                }

                mail.Load(body.ToString(), headersonly);

                x.Add(mail);
            }

            IdleResume();
            return(x.ToArray());
        }
예제 #16
0
 private void FakeReceiveMail(string mailText)
 {
     var msg = new MailMessage();
     msg.Load(mailText);
     messageChannel.Publish(msg);
 }
예제 #17
0
        public void RecognizeHttpsLink()
        {
            var msg = new MailMessage();
            msg.Load(@"Delivered-To: [email protected]
            Received: by 10.229.51.77 with SMTP id c13cs138895qcg;
            Fri, 2 Dec 2011 07:07:47 -0800 (PST)
            Date: Fri, 02 Dec 2011 16:07:44 +0100
            From: Sender <*****@*****.**>
            To: [email protected]
            Message-ID: <*****@*****.**>
            X-Mailer: Dada Mail 4.6.0 Stable - 08/07/11
            Content-type: multipart/alternative; boundary="+"\"_----------=_132282841491260\"" + @"; charset=UTF-8
            Content-Transfer-Encoding: binary
            MIME-Version: 1.0
            Subject: Nice video for you

            This is a multi-part message in MIME format.

            --_----------=_132282841491260
            MIME-Version: 1.0
            Content-Transfer-Encoding: quoted-printable
            Content-Type: text/plain; charset=UTF-8
            Date: Fri, 2 Dec 2011 13:20:14 +0100

            Check this: https://www.youtube.com/watch?feature=embedded_player&v=8HhncO6w4Pc

            --_----------=_132282841491260--");
            input.Publish (msg);

            Assert.AreEqual(1, sink.Messages.Count);
            var clip = sink.Messages[0];
            Assert.AreEqual("8HhncO6w4Pc", clip.ID);
            Assert.AreEqual("Sender", clip.Submitter);
        }
예제 #18
0
        private AE.Net.Mail.MailMessage GetMessage(string raw)
        {
            var msg = new AE.Net.Mail.MailMessage();
            msg.Load(raw, false);

            return msg;
        }
예제 #19
0
        public virtual MailMessage[] GetMessages(string start, string end, bool uid, bool headersonly, bool setseen)
        {
            var x = new List<MailMessage>();

            GetMessages(start, end, uid, headersonly, setseen, (stream, size, imapHeaders) => {
                var mail = new MailMessage { Encoding = Encoding };
                mail.Size = size;

                if (imapHeaders["UID"] != null)
                    mail.Uid = imapHeaders["UID"];

                if (imapHeaders["Flags"] != null)
                    mail.SetFlags(imapHeaders["Flags"]);

                mail.Load(_Stream, headersonly, mail.Size);

                foreach (var key in imapHeaders.AllKeys.Except(new[] { "UID", "Flags", "BODY[]", "BODY[HEADER]" }, StringComparer.OrdinalIgnoreCase))
                    mail.Headers.Add(key, new HeaderValue(imapHeaders[key]));

                x.Add(mail);

                return mail;
            });

            return x.ToArray();
        }
예제 #20
0
        public virtual MailMessage[] GetMessages(string start, string end, bool uid, bool headersonly, bool setseen)
        {
            CheckMailboxSelected();
            IdlePause();

            string tag     = GetTag();
            string command = tag + (uid ? "UID " : null)
                             + "FETCH " + start + ":" + end + " ("
                             + _FetchHeaders + "UID FLAGS BODY"
                             + (setseen ? ".PEEK" : null)
                             + "[" + (headersonly ? "HEADER" : null) + "])";

            string response;
            var    x = new List <MailMessage>();

            SendCommand(command);
            while (true)
            {
                response = GetResponse();
                if (string.IsNullOrEmpty(response) || response.Contains(tag + "OK"))
                {
                    break;
                }

                if (response[0] != '*' || !response.Contains("FETCH ("))
                {
                    continue;
                }

                var mail = new MailMessage {
                    Encoding = Encoding
                };
                var imapHeaders = ParseImapHeader(response.Substring(response.IndexOf('(') + 1));
                mail.Size = (imapHeaders["BODY[HEADER]"] ?? imapHeaders["BODY[]"]).Trim('{', '}').ToInt();

                if (imapHeaders["UID"] != null)
                {
                    mail.Uid = imapHeaders["UID"];
                }

                if (imapHeaders["Flags"] != null)
                {
                    mail.SetFlags(imapHeaders["Flags"]);
                }


                foreach (var key in imapHeaders.AllKeys.Except(new[] { "UID", "Flags", "BODY[]", "BODY[HEADER]" }, StringComparer.OrdinalIgnoreCase))
                {
                    mail.Headers.Add(key, new HeaderValue(imapHeaders[key]));
                }

                //using (var body = new System.IO.MemoryStream()) {
                //  int remaining = mail.Size;
                //  var buffer = new byte[8192];
                //  int read;
                //  while (remaining > 0) {
                //    read = _Stream.Read(buffer, 0, Math.Min(remaining, buffer.Length));
                //    body.Write(buffer, 0, read);
                //    remaining -= read;
                //  }

                //  var next = Convert.ToChar(_Stream.ReadByte());
                //  System.Diagnostics.Debug.Assert(next == ')');

                //  body.Position = 0;
                //  mail.Load(body, headersonly);
                //}

                mail.Load(_Stream, headersonly, mail.Size);

                var n = Convert.ToChar(_Stream.ReadByte());
                System.Diagnostics.Debug.Assert(n == ')');

                x.Add(mail);
            }

            IdleResume();
            return(x.ToArray());
        }
예제 #21
0
        public MailMessage[] GetMessages(string start, string end, bool uid, bool headersonly, bool setseen)
        {
            CheckMailboxSelected();
            IdlePause();

            string UID, HEADERS, SETSEEN;

            UID = HEADERS = SETSEEN = String.Empty;
            if (uid)
            {
                UID = "UID ";
            }
            if (headersonly)
            {
                HEADERS = "HEADER";
            }
            if (setseen)
            {
                SETSEEN = ".PEEK";
            }
            string tag      = GetTag();
            string command  = tag + UID + "FETCH " + start + ":" + end + " (UID RFC822.SIZE FLAGS BODY" + SETSEEN + "[" + HEADERS + "])";
            string response = SendCommandGetResponse(command);
            var    x        = new List <MailMessage>();
            string reg      = @"\* \d+ FETCH.*?BODY.*?\{(\d+)\}";
            Match  m        = Regex.Match(response, reg);

            while (m.Groups.Count > 1)
            {
                int         bodylen = Convert.ToInt32(m.Groups[1].ToString());
                MailMessage mail    = new MailMessage();
                char[]      body    = new char[bodylen];
                int         total   = 0;
                while (total < bodylen)
                {
                    int read = _Reader.Read(body, total, bodylen - total);
                    total += read;
                }

                string message = new string(body);

                Match m2 = Regex.Match(response, @"UID (\d+)");
                if (m2.Groups[1] != null)
                {
                    mail.Uid = m2.Groups[1].ToString();
                }
                m2 = Regex.Match(response, @"FLAGS \((.*?)\)");
                if (m2.Groups[1] != null)
                {
                    mail.SetFlags(m2.Groups[1].ToString());
                }
                m2 = Regex.Match(response, @"RFC822\.SIZE (\d+)");
                if (m2.Groups[1] != null)
                {
                    mail.Size = Convert.ToInt32(m2.Groups[1].ToString());
                }
                mail.Load(new string(body), headersonly);
                x.Add(mail);
                response = _Reader.ReadLine(); // read last line terminated by )
                response = _Reader.ReadLine(); // read next line
                m        = Regex.Match(response, reg);
            }

            IdleResume();
            return(x.ToArray());
        }
예제 #22
0
        public MailMessage[] GetMessages(string start, string end, bool uid, bool headersonly, bool setseen)
        {
            CheckMailboxSelected();
            IdlePause();

            string UID, HEADERS, SETSEEN;

            UID = HEADERS = SETSEEN = String.Empty;
            if (uid)
            {
                UID = "UID ";
            }
            if (headersonly)
            {
                HEADERS = "HEADER";
            }
            if (setseen)
            {
                SETSEEN = ".PEEK";
            }
            string tag      = GetTag();
            string command  = tag + UID + "FETCH " + start + ":" + end + " (UID RFC822.SIZE FLAGS BODY" + SETSEEN + "[" + HEADERS + "])";
            string response = SendCommandGetResponse(command);
            var    x        = new List <MailMessage>();
            string reg      = @"\* \d+ FETCH.*?BODY.*?\{(\d+)\}";
            Match  m        = Regex.Match(response, reg);
            string bodies   = String.Empty;

            while (m.Groups.Count > 1)
            {
                int         bodyremaininglen = Convert.ToInt32(m.Groups[1].ToString());
                MailMessage mail             = new MailMessage();
                //char[] body = new char[bodylen];
                string body = String.Empty;
                while (bodyremaininglen > 0)
                {
                    bodies += GetResponse();
                    if (bodyremaininglen < bodies.Length)
                    {
                        body            += bodies.Substring(0, bodyremaininglen);
                        bodyremaininglen = 0;
                        bodies           = bodies.Remove(0);
                    }
                    else
                    {
                        body             += bodies + Environment.NewLine;
                        bodyremaininglen -= bodies.Length + 2; //extra 2 for CRLF
                        bodies            = "";
                    }
                }

                Match m2 = Regex.Match(response, @"UID (\d+)");
                if (m2.Groups[1] != null)
                {
                    mail.Uid = m2.Groups[1].ToString();
                }
                m2 = Regex.Match(response, @"FLAGS \((.*?)\)");
                if (m2.Groups[1] != null)
                {
                    mail.SetFlags(m2.Groups[1].ToString());
                }
                m2 = Regex.Match(response, @"RFC822\.SIZE (\d+)");
                if (m2.Groups[1] != null)
                {
                    mail.Size = Convert.ToInt32(m2.Groups[1].ToString());
                }
                mail.Load(body, headersonly);
                x.Add(mail);
                response = GetResponse(); // read last line terminated by )
                response = GetResponse(); // read next line
                m        = Regex.Match(response, reg);
            }

            IdleResume();
            return(x.ToArray());
        }
예제 #23
0
        public MailMessage[] GetMessages(string start, string end, bool uid, bool headersonly, bool setseen, string[] fields)
        {
            CheckMailboxSelected();
            IdlePause();

            string fieldsStr = (fields != null
                                 ? (".FIELDS ("
                                    + String.Join(" ", fields)
                                    + ")")
                                 : "");
            string tag     = GetTag();
            string command = tag + (uid ? "UID " : null)
                             + "FETCH " + start + ":" + end + " ("
                             + _FetchHeaders + "UID FLAGS BODY"
                             + (setseen ? ".PEEK" : null)
                             + "[" + (headersonly ? ("HEADER" + fieldsStr) : null)
                             + "])";

            string response;
            var    x = new List <MailMessage>();

            SendCommand(command);
            while (true)
            {
                response = GetResponse();
                if (string.IsNullOrEmpty(response) || response.Contains(tag + "OK"))
                {
                    break;
                }

                if (response[0] != '*' || !response.Contains("FETCH ("))
                {
                    continue;
                }

                var mail = new MailMessage {
                    Encoding = Encoding
                };
                var regex = new Regex(@"UID\s(?<uid>[0-9]*)\sFLAGS\s\((?<flags>.*?)\)\sBODY\[.*?\]\s\{(?<size>[0-9]*)\}");
                var match = regex.Match(response);
                //var imapHeaders = ParseImapHeader(response.Substring(response.IndexOf('(') + 1));
                mail.Size = match.Groups["size"].Value.ToInt();

                if (match.Groups["uid"].Success)
                {
                    mail.Uid = match.Groups["uid"].Value;
                }

                if (match.Groups["flags"].Success)
                {
                    mail.SetFlags(match.Groups["flags"].Value);
                }

                /*
                 * foreach (
                 *  var key in
                 *      imapHeaders.AllKeys.Except(new[] {"UID", "Flags", "BODY[]", "BODY[HEADER]"},
                 *                                 StringComparer.OrdinalIgnoreCase))
                 *  mail.Headers.Add(key, new HeaderValue(imapHeaders[key]));
                 */
                //using (var body = new System.IO.MemoryStream()) {
                //  int remaining = mail.Size;
                //  var buffer = new byte[8192];
                //  int read;
                //  while (remaining > 0) {
                //    read = _Stream.Read(buffer, 0, Math.Min(remaining, buffer.Length));
                //    body.Write(buffer, 0, read);
                //    remaining -= read;
                //  }

                //  var next = Convert.ToChar(_Stream.ReadByte());
                //  System.Diagnostics.Debug.Assert(next == ')');

                //  body.Position = 0;
                //  mail.Load(body, headersonly);
                //}

                mail.Load(_Stream, headersonly, mail.Size);

                x.Add(mail);
            }

            IdleResume();
            return(x.ToArray());
        }
예제 #24
0
        public MailMessage[] GetMessages(string start, string end, bool uid, bool headersonly, bool setseen)
        {
            CheckMailboxSelected();
              IdlePause();

              string UID, HEADERS, SETSEEN;
              UID = HEADERS = SETSEEN = String.Empty;
              if (uid) UID = "UID ";
              if (headersonly) HEADERS = "HEADER";
              if (setseen) SETSEEN = ".PEEK";
              string tag = GetTag();
              string command = tag + UID + "FETCH " + start + ":" + end + " (UID RFC822.SIZE FLAGS BODY" + SETSEEN + "[" + HEADERS + "])";
              string response = SendCommandGetResponse(command);
              var x = new List<MailMessage>();
              string reg = @"\* \d+ FETCH.*?BODY.*?\{(\d+)\}";
              Match m = Regex.Match(response, reg);
              while (m.Groups.Count > 1) {
            int bodylen = Convert.ToInt32(m.Groups[1].ToString());
            MailMessage mail = new MailMessage();
            char[] body = new char[bodylen];
            int total = 0;
            while (total < bodylen) {
              int read = _Reader.Read(body, total, bodylen - total);
              total += read;
            }

            string message = new string(body);

            Match m2 = Regex.Match(response, @"UID (\d+)");
            if (m2.Groups[1] != null) mail.Uid = m2.Groups[1].ToString();
            m2 = Regex.Match(response, @"FLAGS \((.*?)\)");
            if (m2.Groups[1] != null) mail.SetFlags(m2.Groups[1].ToString());
            m2 = Regex.Match(response, @"RFC822\.SIZE (\d+)");
            if (m2.Groups[1] != null) mail.Size = Convert.ToInt32(m2.Groups[1].ToString());
            mail.Load(new string(body), headersonly);
            x.Add(mail);
            response = _Reader.ReadLine(); // read last line terminated by )
            response = _Reader.ReadLine(); // read next line
            m = Regex.Match(response, reg);
              }

              IdleResume();
              return x.ToArray();
        }
예제 #25
0
        public MailMessage[] GetMessages(string start, string end, bool uid, bool headersonly, bool setseen)
        {
            CheckMailboxSelected();
              IdlePause();

              string tag = GetTag();
              string command = tag + (uid ? "UID " : null)
            + "FETCH " + start + ":" + end + " ("
            + _FetchHeaders + "UID RFC822.SIZE FLAGS BODY"
            + (setseen ? ".PEEK" : null)
            + "[" + (headersonly ? "HEADER" : null) + "])";

              string response;
              var x = new List<MailMessage>();

              SendCommand(command);
              while (true) {
            response = GetResponse();
            if (string.IsNullOrEmpty(response) || response.Contains(tag + "OK"))
              break;

            if (response[0] != '*' || !response.Contains("FETCH ("))
              continue;

            var mail = new MailMessage();
            var imapHeaders = ParseImapHeader(response.Substring(response.IndexOf('(') + 1));
            if (imapHeaders["UID"] != null)
              mail.Uid = imapHeaders["UID"];

            if (imapHeaders["Flags"] != null)
              mail.SetFlags(imapHeaders["Flags"]);

            if (imapHeaders["RFC822.SIZE"] != null)
              mail.Size = imapHeaders["RFC822.SIZE"].ToInt();

            foreach (var key in imapHeaders.AllKeys.Except(new[] { "UID", "Flags", "RFC822.SIZE", "BODY[]", "BODY[HEADER]" }, StringComparer.OrdinalIgnoreCase))
              mail.Headers.Add(key, new HeaderValue(imapHeaders[key]));

            int bodySize = (imapHeaders["BODY[HEADER]"] ?? imapHeaders["BODY[]"]).Trim('{', '}').ToInt();

            int size = Math.Min(bodySize, mail.Size > 0 ? mail.Size : bodySize);
            var body = new StringBuilder();
            var buffer = new char[8192];
            int read;
            while (size > 0) {
              read = _Reader.Read(buffer, 0, Math.Min(size, buffer.Length));
              body.Append(buffer, 0, read);
              size -= read;
              if (size == 0) {
            if (_Reader.Peek() != ')') {
              size = Math.Max(bodySize, mail.Size) - Math.Min(bodySize, mail.Size > 0 ? mail.Size : bodySize);
              bodySize = Math.Max(bodySize, mail.Size);
            }
              }
            }

            mail.Load(body.ToString(), headersonly);

            x.Add(mail);
              }

              IdleResume();
              return x.ToArray();
        }
예제 #26
0
        public void GetMessages(string start, string end, bool uid, bool uidsonly, bool headersonly, bool setseen, Action<MailMessage> processCallback)
        {
            GetMessages(start, end, uid, uidsonly, headersonly, setseen, (stream, size, imapHeaders) =>
            {
                var mail = new MailMessage { Encoding = Encoding };
                mail.Size = size;

                if (imapHeaders["UID"] != null)
                    mail.Uid = imapHeaders["UID"];

                if (imapHeaders["Flags"] != null)
                    mail.SetFlags(imapHeaders["Flags"]);

                mail.Load(stream, headersonly, mail.Size);

                foreach (var key in imapHeaders.AllKeys.Except(new[] { "UID", "Flags", "BODY[]", "BODY[HEADER]" }, StringComparer.OrdinalIgnoreCase))
                    mail.Headers.Add(key, new HeaderValue(imapHeaders[key]));

                processCallback(mail);

                return mail;
            });
        }
예제 #27
-1
		public virtual MailMessage GetMessage(string uid, bool headersOnly = false) {
			CheckConnectionStatus();
			var line = SendCommandGetResponse(string.Format(headersOnly ? "TOP {0} 0" : "RETR {0}", uid));
			var size = rxOctets.Match(line).Groups[1].Value.ToInt();
			CheckResultOK(line);
			var msg = new MailMessage();
			msg.Load(_Stream, headersOnly, size, '.');

			msg.Uid = uid;
			var last = GetResponse();
			if (string.IsNullOrEmpty(last))
			{
				try
				{
					last = GetResponse();
				}
				catch (System.IO.IOException)
				{
					// There was really nothing back to read from the remote server
				}
			}

			if (last != ".") {
#if DEBUG
				System.Diagnostics.Debugger.Break();
#endif
				RaiseWarning(msg, "Expected \".\" in stream, but received \"" + last + "\"");
			}

			return msg;
		}
예제 #28
-1
        public MailMessage[] GetMessages(string start, string end, bool uid, bool headersonly, bool setseen)
        {
            CheckMailboxSelected();
              IdlePause();

              string tag = GetTag();
              string command = tag + (uid ? "UID " : null)
            + "FETCH " + start + ":" + end + " ("
            + _FetchHeaders + "UID FLAGS BODY"
            + (setseen ? ".PEEK" : null)
            + "[" + (headersonly ? "HEADER" : null) + "])";

              string response;
              var x = new List<MailMessage>();

              SendCommand(command);
              while (true) {
            response = GetResponse();
            if (string.IsNullOrEmpty(response) || response.Contains(tag + "OK"))
              break;

            if (response[0] != '*' || !response.Contains("FETCH ("))
              continue;

            var mail = new MailMessage { Encoding = Encoding };
            var imapHeaders = ParseImapHeader(response.Substring(response.IndexOf('(') + 1));
            mail.Size = (imapHeaders["BODY[HEADER]"] ?? imapHeaders["BODY[]"]).Trim('{', '}').ToInt();

            if (imapHeaders["UID"] != null)
              mail.Uid = imapHeaders["UID"];

            if (imapHeaders["Flags"] != null)
              mail.SetFlags(imapHeaders["Flags"]);

            foreach (var key in imapHeaders.AllKeys.Except(new[] { "UID", "Flags", "BODY[]", "BODY[HEADER]" }, StringComparer.OrdinalIgnoreCase))
              mail.Headers.Add(key, new HeaderValue(imapHeaders[key]));

            //using (var body = new System.IO.MemoryStream()) {
            //  int remaining = mail.Size;
            //  var buffer = new byte[8192];
            //  int read;
            //  while (remaining > 0) {
            //    read = _Stream.Read(buffer, 0, Math.Min(remaining, buffer.Length));
            //    body.Write(buffer, 0, read);
            //    remaining -= read;
            //  }

            //  var next = Convert.ToChar(_Stream.ReadByte());
            //  System.Diagnostics.Debug.Assert(next == ')');

            //  body.Position = 0;
            //  mail.Load(body, headersonly);
            //}

            mail.Load(_Stream, headersonly, mail.Size);

            var n = Convert.ToChar(_Stream.ReadByte());
            System.Diagnostics.Debug.Assert(n == ')');

            x.Add(mail);
              }

              IdleResume();
              return x.ToArray();
        }