コード例 #1
0
        private MailMessage Draft(MailMessage msg, string uid = null)
        {
            try
            {
                using (var imap = EnsureConnection())
                {
                    imap.SelectMailbox("Drafts");
                    var messageid = Guid.NewGuid() + "@" + DOMAIN;
                    msg.MessageID = messageid;
                    imap.AppendMail(msg);
                    // delete the old message and upload the new one to drafts
                    if (!String.IsNullOrEmpty(uid))
                    {
                        imap.DeleteMessage(uid);
                    }
                    var messages = imap
                                   .Search(SearchCondition.Deleted().Not().And(SearchCondition.Header("Message-ID", msg.MessageID)))
                                   .Select(x => imap.GetMessage(x, true, true));

                    return(messages.FirstOrDefault() ?? msg);
                }
            }
            catch
            {
                throw new HttpException(500, Support.Error_Drafting);
            }
        }
コード例 #2
0
        IImapMessage Extract <TMessage>(AE.Net.Mail.MailMessage info, bool getRawHtml) where TMessage : IImapMessage, new()
        {
            var result = new TMessage
            {
                Date           = info.Date,
                From           = info.From?.Address,
                MessageId      = info.MessageID,
                Bcc            = info.Bcc?.Select(x => x.Address).ToString(", "),
                Cc             = info.Cc?.Select(x => x.Address).ToString(", "),
                DateDownloaded = LocalTime.Now,
                Subject        = info.Subject,
                Body           = info.Body,
                To             = info.To?.Select(x => x.Address).ToString(", ")
            };

            var attachmentList = info.AlternateViews.Cast <Attachment>();

            if (attachmentList.HasMany())
            {
                if (getRawHtml)
                {
                    result.Body = attachmentList.ElementAt(1).Body;
                }
                else
                {
                    result.Body = attachmentList.First().Body;
                }
            }

            result.Attachments = (info.Attachments ?? new List <Attachment>()).Select(attachment => new XElement("Attachment", new XAttribute("FileName", attachment.Filename), new XElement("Bytes", attachment.GetData().ToBase64String()))).ToLinesString();

            return(result);
        }
コード例 #3
0
 public ComposeMail(bool?all, MailMessage msg = null) : this()
 {
     if (msg != null)
     {
         Uid = msg.Uid;
         // forward the message
         if (!all.HasValue)
         {
             To = "";
         }
         // reply all
         else if (all.Value)
         {
             To = String.Join("; ", msg.To.Concat(new[] { msg.From })
                              .Where(x => x.Address.Contains(_profile.Value))
                              .Select(x => SharedRes.Formats.MailAddress.FormatWith(x)));
         }
         // reply one
         else
         {
             To = SharedRes.Formats.MailAddress.FormatWith(msg.From);
         }
         Subject = msg.Subject;
         Body    = "\r\n\r\n--\r\n" + msg.Body;
     }
 }
コード例 #4
0
    public void Execute(EmailMessage message)
    {
        try
        {
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = message.Subject,
                Body    = message.Body,
                From    = new MailAddress(_emailSettings.FromEmail)
            };
            msg.To.Add(new MailAddress(message.ReceiverEmail));
            msg.ReplyTo.Add(msg.From); // Bounces without this!!
            var msgStr = new StringWriter();
            msg.Save(msgStr);

            // Context is a separate bit of code that provides OAuth context;
            // your construction of GmailService will be different from mine.
            _logger.LogDebug(msgStr.ToString());
            var result = _gmail.Users.Messages.Send(new Message
            {
                Raw = Base64UrlEncode(msgStr.ToString())
            }, "me").Execute();
        }
        catch (Exception ex)
        {
            _logger.LogDebug(ex.StackTrace);
        }
    }
コード例 #5
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);
        }
コード例 #6
0
 public ComposeMail(MailMessage msg = null) : this()
 {
     if (msg != null)
     {
         Uid     = msg.Uid;
         To      = String.Join("; ", msg.To.Select(x => SharedRes.Formats.MailAddress.FormatWith(x)));
         Subject = msg.Subject;
         Body    = msg.Body.Replace("\r", "");
     }
 }
コード例 #7
0
        public void GetAllAttachments(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject)
        {
            serviceObject.Properties.InitResultTable();

            System.Data.DataRow dr;
            Helper h = new Helper(serviceBroker);

            string mailbox       = inputs.Where(p => p.Name.Equals("mailbox")).FirstOrDefault().Value.ToString();
            string uid           = string.Empty;
            string subjectfilter = string.Empty;

            uid = inputs.Where(p => p.Name.Equals("uid")).FirstOrDefault().Value.ToString();

            AE.Net.Mail.MailMessage       m           = null;
            List <AE.Net.Mail.Attachment> attachments = new List <AE.Net.Mail.Attachment>();

            try
            {
                using (var ic = h.GetImapClient())
                {
                    m = ic.GetMessage(uid, false);

                    if (m == null)
                    {
                        return;
                    }

                    attachments = m.Attachments as List <AE.Net.Mail.Attachment>;

                    foreach (Attachment a in attachments)
                    {
                        dr = serviceBroker.ServicePackage.ResultTable.NewRow();

                        dr["body"]    = a.Body;
                        dr["charset"] = a.Charset;
                        dr["contenttransferencoding"] = a.ContentTransferEncoding;
                        dr["contenttype"]             = a.ContentType;
                        dr["filename"]   = a.Filename;
                        dr["rawheaders"] = a.RawHeaders;
                        dr["onserver"]   = a.OnServer;

                        dr["mailbox"] = inputs.Where(p => p.Name.Equals("mailbox")).FirstOrDefault().Value.ToString();
                        dr["uid"]     = inputs.Where(p => p.Name.Equals("uid")).FirstOrDefault().Value.ToString();

                        serviceBroker.ServicePackage.ResultTable.Rows.Add(dr);
                    }

                    ic.Disconnect();
                }
            }
            catch (Exception ex)
            {
                //serviceObject.Properties.BindPropertiesToResultTable();
            }
        }
コード例 #8
0
 private MailMessage GetInputMailMessage(AE.Net.Mail.MailMessage message)
 {
     return(new MailMessage
     {
         Date = message.Date,
         Sender = message.From,
         Receivers = message.To,
         Subject = message.Subject,
         Body = message.Body,
         UserAgent = GetUserAgent(message.Raw)
     });
 }
コード例 #9
0
ファイル: Pop3Client.cs プロジェクト: KgDesignes/aenetmail
        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;
        }
コード例 #10
0
ファイル: Pop3Client.cs プロジェクト: spzenk/sfdocsamples
        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;
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: simotaleb/airlink
        static void connection()
        {
            string path   = "../../docs";
            string server = "imap.gmail.com";
            string email  = "";
            string pw     = "";

            try
            {
                using (ImapClient ic = new ImapClient(server, email, pw, AuthMethods.Login, 993, true))
                {
                    ic.SelectMailbox("inbox");
                    Console.WriteLine("running");
                    int x = 0;
                    Lazy <AE.Net.Mail.MailMessage>[] messages = ic.SearchMessages(SearchCondition.Undeleted(), false);

                    foreach (Lazy <AE.Net.Mail.MailMessage> msg in messages)
                    {
                        AE.Net.Mail.MailMessage m = msg.Value;
                        string sender             = m.From.Address;
                        string FileName           = string.Empty;

                        if (sender == "*****@*****.**")
                        {
                            FileName = "../../docs/boardingpass";
                            Directory.CreateDirectory(path);
                            foreach (AE.Net.Mail.Attachment attachment in m.Attachments)
                            {
                                if (attachment.Filename.Contains("invoice") == false)
                                {
                                    x++;
                                    FileName = FileName + x;
                                    attachment.Save(FileName + Path.GetExtension(attachment.Filename));
                                    Pdf2text(FileName);
                                }
                            }

                            sendemail(cl);
                            Directory.Delete(path, true);
                            ic.DeleteMessage(m);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadKey();
            }
        }
コード例 #12
0
ファイル: LinkExtractor.cs プロジェクト: rix0rrr/SiouxTube
        /// <summary>
        /// Parse one message for YouTube links and publish them on the clip channel
        /// if found.
        /// </summary>
        /// <remarks>
        /// Currently only supports one link per mail.
        /// </remarks>
        private void HandleMessage(MailMessage m)
        {
            var match = YouTubeLinkRegex1.Match(MessageAsText(m));
            if (!match.Success) match = YouTubeLinkRegex2.Match(MessageAsText(m));

            if (match.Success)
            {
                var vid = match.Groups["videoid"].Value;
                var clip = new SimpleYouTubeClip(vid, m.From != null ? m.From.DisplayName : "Unknown Sender", DateTime.Now);
                Debug.WriteLine("In message '{0}' found: {1}", m.Subject, clip);
                clipChannel.Publish(clip);
            }
            else
                Debug.WriteLine("Did not find a YouTube link in '" + m.Subject + "'");
        }
コード例 #13
0
 public void MapMailMessage(System.Data.DataRow dr, AE.Net.Mail.MailMessage mmsg)
 {
     dr["bcc"]        = GetAddresses(mmsg.Bcc);
     dr["body"]       = mmsg.Body;
     dr["cc"]         = GetAddresses(mmsg.Cc);
     dr["date"]       = mmsg.Date;
     dr["from"]       = mmsg.From != null ? mmsg.From.Address : "";
     dr["importance"] = mmsg.Importance.ToString();
     dr["replyto"]    = GetAddresses(mmsg.ReplyTo);
     dr["sender"]     = mmsg.Sender != null ? mmsg.Sender.Address : "";
     dr["size"]       = mmsg.Size;
     dr["subject"]    = mmsg.Subject;
     dr["to"]         = GetAddresses(mmsg.To);
     dr["uid"]        = mmsg.Uid;
     //dr["rawmessage"] = m.RawBody;
     //dr["base64emlmessage"] = m.Base64Body;
     dr["attachmentscount"] = mmsg.Attachments != null ? mmsg.Attachments.Count : 0;
 }
コード例 #14
0
ファイル: ParseSpam.cs プロジェクト: XiBeichuan/hydronumerics
		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;
				}
			}
		}
コード例 #15
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);
            }
        }
コード例 #16
0
ファイル: Functions.cs プロジェクト: derekantrican/Assistant
        public static void SendGmail(string to, string subject, string body)
        {
            AuthorizeGmail();

            AE.Net.Mail.MailMessage message = new AE.Net.Mail.MailMessage();
            message.Subject = subject;
            message.Body    = body;
            message.To.Add(new MailAddress(to));
            message.From = new MailAddress(GetUserEmailAddress());

            StringWriter msgStr = new StringWriter();

            message.Save(msgStr);

            UsersResource.MessagesResource             messageResource = gmailService.Users.Messages;
            UsersResource.MessagesResource.SendRequest sendRequest     = messageResource.Send(new Google.Apis.Gmail.v1.Data.Message {
                Raw = Base64UrlEncode(msgStr.ToString())
            }, "me");
            sendRequest.Execute();
        }
コード例 #17
0
ファイル: Pop3Client.cs プロジェクト: alihamza2828/aenetmail
        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;
        }
コード例 #18
0
    //Metodo para enviar mensajes
    public static void SendMessage(string userId, string destinatario, string mensaje, string asunto, GmailService s)
    {
        //Crear mensaje
        var msg = new AE.Net.Mail.MailMessage
        {
            Subject = asunto,
            Body    = mensaje,
            From    = new MailAddress(Usuario.GetProfile(s, userId).EmailAddress)
        };

        msg.To.Add(new MailAddress(destinatario));
        msg.ReplyTo.Add(msg.From);
        var msgStr = new StringWriter();

        msg.Save(msgStr);
        //Enviarlo
        var result = s.Users.Messages.Send(new Message
        {
            Raw = Base64UrlEncode(msgStr.ToString())
        }, "me").Execute();
    }
コード例 #19
0
    public void SendIt()
    {
        var msg = new AE.Net.Mail.MailMessage {
            Subject = "Your Subject",
            Body    = "Hello, World, from Gmail API!",
            From    = new MailAddress("[you]@gmail.com")
        };

        msg.To.Add(new MailAddress("*****@*****.**"));
        msg.ReplyTo.Add(msg.From); // Bounces without this!!
        var msgStr = new StringWriter();

        msg.Save(msgStr);

        var gmail  = new GmailService(MyOwnGoogleOAuthInitializer);
        var result = gmail.Users.Messages.Send(new Message {
            Raw = Base64UrlEncode(msgStr.ToString())
        }, "me").Execute();

        Console.WriteLine("Message ID {0} sent.", result.Id);
    }
コード例 #20
0
        private void HandleMessage(MailMessage message)
        {
            if (message == null) return;

            try
            {
                lock (lockRoot) // One message at a time
                {
                    Debug.WriteLine("Found a message with {1} attachments: {0}", message.Subject, message.Attachments.Count);
                    foreach (var att in message.Attachments.Where(_ => _.IsAttachment))
                    {
                        var ctr = 0;

                        string fullpath;
                        do
                        {
                            ctr++;
                            string filename =
                                "[" + message.From.DisplayName + "] "
                                + Path.GetFileNameWithoutExtension(att.Filename)
                                + (ctr > 1 ? " (" + ctr + ")" : "")
                                + Path.GetExtension(att.Filename);
                            fullpath = Path.Combine(path, filename);
                        }
                        while (File.Exists(fullpath));

                        Debug.WriteLine("Saving {0} to {1}", att.Filename, fullpath);
                        att.Save(fullpath);
                        Debug.WriteLine("Done.");
                    }

                    imap.SetFlags(message.Flags | Flags.Seen, message);
                    imap.DeleteMessage(message);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
コード例 #21
0
        public void Attachment_SavesWithMessage()
        {
            var msg = new AE.Net.Mail.MailMessage()
            {
                From = new System.Net.Mail.MailAddress("*****@*****.**")
            };
            var firstAttachmentContents = "This is a test.";
            var attachment = new Attachment()
            {
                Body = Convert.ToBase64String(Encoding.Default.GetBytes(firstAttachmentContents)),
                ContentTransferEncoding = "base64",
                Encoding = Encoding.ASCII
            };

            attachment.Headers.Add("Content-Type", new HeaderValue(@"text/plain; filename=""Readme.txt"""));
            msg.Attachments.Add(attachment);

            var rnd = new Random();
            var secondAttachmentContents = new byte[rnd.Next(10, 1000)];

            rnd.NextBytes(secondAttachmentContents);
            attachment = new Attachment()
            {
                Body = Convert.ToBase64String(secondAttachmentContents),
                ContentTransferEncoding = "base64",
                Encoding = Encoding.ASCII
            };
            attachment.Headers.Add("Content-Type", new HeaderValue(@"application/binary; filename=""Data.bin"""));
            msg.Attachments.Add(attachment);


            var reparsed = Reparse(msg);

            reparsed.Attachments.Count.ShouldBe(2);
            reparsed.Attachments.First().Filename.ShouldBe("Readme.txt");
            reparsed.Attachments.First().Body.ShouldBe(firstAttachmentContents);
            reparsed.Attachments.Last().Filename.ShouldBe("Data.bin");
            Convert.FromBase64String(reparsed.Attachments.Last().Body).ShouldBe(secondAttachmentContents);
        }
コード例 #22
0
        public ICollection <Message> ReceiveMessages(int returnCount) //TODO needs refectoring try-catch
        {
            imapClient.SelectMailbox("INBOX");
            var messageTotalAmount = imapClient.GetMessageCount();

            if (messageTotalAmount < returnCount)
            {
                returnCount = messageTotalAmount;
            }
            var mailMessageList = new List <AE.Net.Mail.MailMessage>();

            for (int i = messageTotalAmount - 1; i >= messageTotalAmount - returnCount; i--)
            {
                AE.Net.Mail.MailMessage message = imapClient.GetMessage(i);
                mailMessageList.Add(message);
            }
            var resultMessageList = new List <Message>();

            mailMessageList.ForEach(mail => resultMessageList.Add(new Message(mail)));

            return(resultMessageList);
        }
コード例 #23
0
        private static void BeginCopy(ImapClient source, Mailbox mailbox, ImapClient destination)
        {
            var srcMsgCount = source.GetMessageCount(mailbox.Name);

            if (srcMsgCount > 0)
            {
                source.SelectMailbox(mailbox.Name);
                Console.WriteLine("Getting source mesages " + srcMsgCount);
                var srcMsgs      = source.GetMessages(0, 5, false);
                var destMsgCount = destination.GetMessageCount(mailbox.Name);
                if (destMsgCount > 0)
                {
                    destination.SelectMailbox(mailbox.Name);
                    var destMsgs = destination.GetMessages(0, destMsgCount);
                    CopyEmails(srcMsgs, destMsgs, destination, mailbox);
                }
                else
                {
                    var destMsgs = new AE.Net.Mail.MailMessage[0];
                    CopyEmails(srcMsgs, destMsgs, destination, mailbox);
                }
            }
        }
コード例 #24
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);
        }
コード例 #25
0
ファイル: ImapClient.cs プロジェクト: Comp-Ex/aenetmail
        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();
        }
コード例 #26
0
ファイル: Parsing.cs プロジェクト: bobeverland/aenetmail
        private AE.Net.Mail.MailMessage GetMessage(string raw)
        {
            var msg = new AE.Net.Mail.MailMessage();
            msg.Load(raw, false);

            return msg;
        }
コード例 #27
0
ファイル: Parsing.cs プロジェクト: harold4/aenetmail
        public void Attachment_SavesWithMessage()
        {
            var msg = new AE.Net.Mail.MailMessage()
            {
                From = new System.Net.Mail.MailAddress("*****@*****.**")
            };
            var firstAttachmentContents = "This is a test.";
            var attachment = new Attachment()
            {
                Body = Convert.ToBase64String(Encoding.Default.GetBytes(firstAttachmentContents)),
                ContentTransferEncoding = "base64",
                Encoding = Encoding.ASCII
            };
            attachment.Headers.Add("Content-Type", new HeaderValue(@"text/plain; filename=""Readme.txt"""));
            msg.Attachments.Add(attachment);

            var rnd = new Random();
            var secondAttachmentContents = new byte[rnd.Next(10, 1000)];
            rnd.NextBytes(secondAttachmentContents);
            attachment = new Attachment()
            {
                Body = Convert.ToBase64String(secondAttachmentContents),
                ContentTransferEncoding = "base64",
                Encoding = Encoding.ASCII
            };
            attachment.Headers.Add("Content-Type", new HeaderValue(@"application/binary; filename=""Data.bin"""));
            msg.Attachments.Add(attachment);

            var reparsed = Reparse(msg);
            reparsed.Attachments.Count.ShouldBe(2);
            reparsed.Attachments.First().Filename.ShouldBe("Readme.txt");
            reparsed.Attachments.First().Body.ShouldBe(firstAttachmentContents);
            reparsed.Attachments.Last().Filename.ShouldBe("Data.bin");
            Convert.FromBase64String(reparsed.Attachments.Last().Body).ShouldBe(secondAttachmentContents);
        }
コード例 #28
0
ファイル: ImapClient.cs プロジェクト: ogazitt/aenetmail
        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();
        }
コード例 #29
0
        private static MailMessage GetMessage(string uid)
        {
            MailMessage response = new MailMessage();

            using (var imap = new ImapClient(Host, UserName, Password, ImapClient.AuthMethods.Login, Port, false))
            {
                response = imap.GetMessage(uid, false);
            }

            return response;
        }
コード例 #30
0
ファイル: EmailMonitor.cs プロジェクト: kneedels/gunderson
        private bool ShouldFireEvent(MailMessage message)
        {
            HeaderValue headerValue;

            if (message.Headers.TryGetValue(VerificationHeaderName, out headerValue))
            {
                return headerValue.Value == VerificationHeaderValue;
            }

            return false;
        }
コード例 #31
0
 private void FakeReceiveMail(string mailText)
 {
     var msg = new MailMessage();
     msg.Load(mailText);
     messageChannel.Publish(msg);
 }
コード例 #32
0
ファイル: ImapClient.cs プロジェクト: meehi/aenetmail
        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();
        }
コード例 #33
0
ファイル: ImapClient.cs プロジェクト: meehi/aenetmail
 public void DeleteMessage(MailMessage msg)
 {
     DeleteMessage(msg.Uid);
 }
コード例 #34
0
ファイル: ImapClient.cs プロジェクト: Geograph-us/aenetmail
 public virtual void AppendMail(MailMessage email, string mailbox = null)
 {
     var body = new StringBuilder();
     using (var txt = new System.IO.StringWriter(body))
         email.Save(txt);
     AppendMail(body.ToString(), email.RawFlags.Length > 0 ? email.Flags : (Flags?)null, mailbox);
 }
コード例 #35
0
 public static void deleteMail(AE.Net.Mail.MailMessage m)
 {
     mImapClient.DeleteMessage(m);
 }
コード例 #36
0
ファイル: EmailMonitor.cs プロジェクト: kneedels/gunderson
        private void ProcessAndFireEvent(MailMessage message)
        {
            if (!ShouldFireEvent(message))
            {
                return;
            }

            EmailData data = new EmailData();

            data.From = message.From.DisplayName;

            data.Subject = ScrubAndShortenSubject(message.Subject);
            data.Time = message.Date;
            data.ContentSummary = ScrubAndShortenBody(message.Body);

            Task.Factory.StartNew(() =>
                {
                    lock (this)
                    {
                        EmailReceived(data);
                    }
                });
        }
コード例 #37
0
ファイル: ImapClient.cs プロジェクト: ogazitt/aenetmail
        public void AppendMail(string mailbox, MailMessage email)
        {
            IdlePause();

              string flags = String.Empty;
              string size = (email.Body.Length - 1).ToString();
              if (email.RawFlags.Length > 0) {
            flags = string.Concat("(", string.Join(" ", email.Flags), ")");
              }
              string command = GetTag() + "APPEND " + mailbox.QuoteString() + " " + flags + " {" + size + "}";
              string response = SendCommandGetResponse(command);
              if (response.StartsWith("+")) {
            response = SendCommandGetResponse(email.Body);
              }
              IdleResume();
        }
コード例 #38
0
        public void GetAttachment(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject)
        {
            serviceObject.Properties.InitResultTable();

            Helper h = new Helper(serviceBroker);

            string mailbox       = inputs.Where(p => p.Name.Equals("mailbox")).FirstOrDefault().Value.ToString();
            string uid           = string.Empty;
            string subjectfilter = string.Empty;
            int    index         = -1;

            uid   = inputs.Where(p => p.Name.Equals("uid")).FirstOrDefault().Value.ToString();
            index = int.Parse(inputs.Where(p => p.Name.Equals("attachmentindex")).FirstOrDefault().Value.ToString());

            AE.Net.Mail.MailMessage       m           = null;
            List <AE.Net.Mail.Attachment> attachments = new List <AE.Net.Mail.Attachment>();

            try
            {
                using (var ic = h.GetImapClient())
                {
                    m = ic.GetMessage(uid, false);

                    if (m == null)
                    {
                        return;
                    }

                    attachments = m.Attachments as List <AE.Net.Mail.Attachment>;

                    AE.Net.Mail.Attachment a = null;

                    if (index == -1 || index > attachments.Count)
                    {
                        return;
                    }
                    a = attachments[index];

                    if (a == null)
                    {
                        return;
                    }

                    returns.Where(p => p.Name.ToLower().Equals("body")).FirstOrDefault().Value    = a.Body;
                    returns.Where(p => p.Name.ToLower().Equals("charset")).FirstOrDefault().Value = a.Charset;
                    returns.Where(p => p.Name.ToLower().Equals("contenttransferencoding")).FirstOrDefault().Value = a.ContentTransferEncoding;
                    returns.Where(p => p.Name.ToLower().Equals("contenttype")).FirstOrDefault().Value             = a.ContentType;
                    returns.Where(p => p.Name.ToLower().Equals("filename")).FirstOrDefault().Value        = a.Filename;
                    returns.Where(p => p.Name.ToLower().Equals("rawheaders")).FirstOrDefault().Value      = a.RawHeaders;
                    returns.Where(p => p.Name.ToLower().Equals("onserver")).FirstOrDefault().Value        = a.OnServer;
                    returns.Where(p => p.Name.ToLower().Equals("mailbox")).FirstOrDefault().Value         = inputs.Where(p => p.Name.Equals("mailbox")).FirstOrDefault().Value.ToString();
                    returns.Where(p => p.Name.ToLower().Equals("uid")).FirstOrDefault().Value             = inputs.Where(p => p.Name.Equals("uid")).FirstOrDefault().Value.ToString();;
                    returns.Where(p => p.Name.ToLower().Equals("attachmentindex")).FirstOrDefault().Value = inputs.Where(p => p.Name.Equals("attachmentindex")).FirstOrDefault().Value.ToString();;

                    ic.Disconnect();
                }
            }
            catch (Exception ex)
            {
                //serviceObject.Properties.BindPropertiesToResultTable();
            }
            serviceObject.Properties.BindPropertiesToResultTable();
        }
コード例 #39
0
ファイル: Program.cs プロジェクト: ogazitt/TaskStore
        static void ProcessMessage(MailMessage m)
        {
            string from = m.From.Address;
            if (from == null || from == "")
                return;
            string taskName = GetSubject(m.Subject);
            string body = m.Body;
            if (body == null || body == "")
                body = m.BodyHtml;

            var users = TaskStore.Users.Where(u => u.Email == from).ToList();
            foreach (var u in users)
            {
                Guid? list = GetList(u, body);
                if (list != null)
                {
                    DateTime now = DateTime.Now;
                    Task t = new Task()
                    {
                        ID = Guid.NewGuid(),
                        Name = taskName,
                        TaskListID = (Guid) list,
                        Created = now,
                        LastModified = now,
                    };

                    // extract structured fields such as due date, e-mail, website, phone number
                    ParseFields(t, body);

                    var task = TaskStore.Tasks.Add(t);
                    int rows = TaskStore.SaveChanges();

                    if (rows > 0)
                    {
                        Console.WriteLine("added " + t.Name);
                    }
                }
            }
        }
コード例 #40
0
        public void GetMessages(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject)
        {
            serviceObject.Properties.InitResultTable();

            System.Data.DataRow dr;
            Helper h = new Helper(serviceBroker);

            string subjectfilter = string.Empty;
            string bodyfilter    = string.Empty;
            string fromfilter    = string.Empty;

            string startindex       = string.Empty;
            string numberofmessages = string.Empty;

            string mailbox     = inputs.Where(p => p.Name.Equals("mailbox")).FirstOrDefault().Value.ToString();
            bool   headersonly = bool.Parse(inputs.Where(p => p.Name.Equals("headersonly")).FirstOrDefault().Value.ToString());
            bool   setseen     = bool.Parse(inputs.Where(p => p.Name.Equals("setseen")).FirstOrDefault().Value.ToString());;

            AE.Net.Mail.MailMessage mtemp = new AE.Net.Mail.MailMessage();
            try
            {
                using (var ic = h.GetImapClient())
                {
                    AE.Net.Mail.MailMessage[]        m  = null;
                    Lazy <AE.Net.Mail.MailMessage>[] mm = null;

                    bool isLazy = false;

                    switch (serviceObject.Methods[0].Name.ToLower())
                    {
                    case "getallmessages":
                        m      = ic.GetMessages(0, ic.GetMessageCount(), headersonly, setseen);
                        isLazy = false;
                        break;

                    case "getmessages":
                        startindex       = inputs.Where(p => p.Name.Equals("startindex")).FirstOrDefault().Value.ToString();
                        numberofmessages = inputs.Where(p => p.Name.Equals("numberofmessages")).FirstOrDefault().Value.ToString();
                        m      = ic.GetMessages(int.Parse(startindex), int.Parse(numberofmessages), headersonly, setseen);
                        isLazy = false;
                        break;

                    case "searchmessagesbysubject":
                        subjectfilter = inputs.Where(p => p.Name.Equals("subjectfilter")).FirstOrDefault().Value.ToString();
                        mm            = ic.SearchMessages(SearchCondition.Undeleted().And(SearchCondition.Subject(subjectfilter)));
                        isLazy        = true;
                        break;

                    case "searchmessagesbybody":
                        bodyfilter = inputs.Where(p => p.Name.Equals("bodyfilter")).FirstOrDefault().Value.ToString();
                        mm         = ic.SearchMessages(SearchCondition.Undeleted().And(SearchCondition.Body(bodyfilter))).ToArray();
                        isLazy     = true;
                        break;

                    case "searchmessagesbyfrom":
                        fromfilter = inputs.Where(p => p.Name.Equals("fromfilter")).FirstOrDefault().Value.ToString();
                        mm         = ic.SearchMessages(SearchCondition.Undeleted().And(SearchCondition.From(fromfilter))).ToArray();
                        isLazy     = true;
                        break;
                    }

                    //AE.Net.Mail.MailMessage[] mm = ic.GetMessages(0, ic.GetMessageCount(), headersonly, setseen);

                    if (isLazy)
                    {
                        foreach (System.Lazy <AE.Net.Mail.MailMessage> msg in mm)
                        {
                            AE.Net.Mail.MailMessage mmsg = msg.Value;
                            dr = serviceBroker.ServicePackage.ResultTable.NewRow();

                            MapMailMessage(dr, mmsg);

                            dr["mailbox"]     = mailbox;
                            dr["headersonly"] = headersonly;
                            dr["setseen"]     = setseen;

                            switch (serviceObject.Methods[0].Name.ToLower())
                            {
                            case "searchmessagesbysubject":
                                dr["subjectfilter"] = subjectfilter;
                                break;

                            case "searchmessagesbybody":
                                dr["bodyfilter"] = bodyfilter;
                                break;

                            case "searchmessagesbyfrom":
                                dr["fromfilter"] = fromfilter;
                                break;
                            }


                            dr["startindex"]       = startindex;
                            dr["numberofmessages"] = numberofmessages;

                            serviceBroker.ServicePackage.ResultTable.Rows.Add(dr);
                        }
                    }
                    else
                    {
                        foreach (AE.Net.Mail.MailMessage msg in m.OrderByDescending(p => p.Date))
                        {
                            mtemp = msg;
                            dr    = serviceBroker.ServicePackage.ResultTable.NewRow();

                            MapMailMessage(dr, msg);

                            dr["mailbox"]     = mailbox;
                            dr["headersonly"] = headersonly;
                            dr["setseen"]     = setseen;
                            switch (serviceObject.Methods[0].Name.ToLower())
                            {
                            case "searchmessagesbysubject":
                                dr["subjectfilter"] = subjectfilter;
                                break;

                            case "searchmessagesbybody":
                                dr["bodyfilter"] = bodyfilter;
                                break;

                            case "searchmessagesbyfrom":
                                dr["fromfilter"] = fromfilter;
                                break;
                            }
                            dr["startindex"]       = startindex;
                            dr["numberofmessages"] = numberofmessages;

                            serviceBroker.ServicePackage.ResultTable.Rows.Add(dr);
                        }
                    }

                    ic.Disconnect();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(mtemp.Subject);
                //serviceObject.Properties.BindPropertiesToResultTable();
            }
            //serviceObject.Properties.BindPropertiesToResultTable();
        }
コード例 #41
0
ファイル: ImapClient.cs プロジェクト: harold4/aenetmail
        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;
            });
        }
コード例 #42
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);
        }
コード例 #43
0
ファイル: Parsing.cs プロジェクト: harold4/aenetmail
        private MailMessage Reparse(MailMessage msg)
        {
            var sb = new StringBuilder();
            using (var w = new StringWriter(sb))
            {
                msg.Save(w);
            }
            // System.Diagnostics.Debug.WriteLine(sb.ToString());

            var parsedMessage = GetMessage(sb.ToString());
            return parsedMessage;
        }
コード例 #44
0
        public void GetMessageBy(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject)
        {
            serviceObject.Properties.InitResultTable();

            Helper h = new Helper(serviceBroker);

            string mailbox       = inputs.Where(p => p.Name.Equals("mailbox")).FirstOrDefault().Value.ToString();
            string uid           = string.Empty;
            string subjectfilter = string.Empty;

            AE.Net.Mail.MailMessage m = null;
            try
            {
                using (var ic = h.GetImapClient())
                {
                    switch (serviceObject.Methods[0].Name.ToLower())
                    {
                    case "getmessagebyuid":
                        uid = inputs.Where(p => p.Name.Equals("uid")).FirstOrDefault().Value.ToString();
                        m   = ic.GetMessage(uid, false);
                        break;

                    case "getmessagebysubject":
                        subjectfilter = inputs.Where(p => p.Name.Equals("subjectfilter")).FirstOrDefault().Value.ToString();
                        Lazy <AE.Net.Mail.MailMessage>[] mm = ic.SearchMessages(SearchCondition.Undeleted().And(SearchCondition.Subject(subjectfilter)));
                        Lazy <AE.Net.Mail.MailMessage>   lm = mm.OrderByDescending(p => p.Value.Date).Where(p => p.Value.Subject.ToLower().Equals(subjectfilter)).FirstOrDefault();

                        if (lm != null && lm.Value != null)
                        {
                            m = lm.Value;
                        }

                        break;
                    }

                    // = ic.GetMessage(uid, false);

                    if (m == null)
                    {
                        return;
                    }

                    returns.Where(p => p.Name.ToLower().Equals("bcc")).FirstOrDefault().Value        = GetAddresses(m.Bcc);
                    returns.Where(p => p.Name.ToLower().Equals("body")).FirstOrDefault().Value       = m.Body;
                    returns.Where(p => p.Name.ToLower().Equals("cc")).FirstOrDefault().Value         = GetAddresses(m.Cc);
                    returns.Where(p => p.Name.ToLower().Equals("date")).FirstOrDefault().Value       = m.Date;
                    returns.Where(p => p.Name.ToLower().Equals("from")).FirstOrDefault().Value       = m.From != null ? m.From.Address : "";
                    returns.Where(p => p.Name.ToLower().Equals("importance")).FirstOrDefault().Value = m.Importance.ToString();
                    returns.Where(p => p.Name.ToLower().Equals("replyto")).FirstOrDefault().Value    = GetAddresses(m.ReplyTo);
                    returns.Where(p => p.Name.ToLower().Equals("sender")).FirstOrDefault().Value     = m.Sender != null ? m.Sender.Address : "";
                    returns.Where(p => p.Name.ToLower().Equals("size")).FirstOrDefault().Value       = m.Size;
                    returns.Where(p => p.Name.ToLower().Equals("subject")).FirstOrDefault().Value    = m.Subject;
                    returns.Where(p => p.Name.ToLower().Equals("to")).FirstOrDefault().Value         = GetAddresses(m.To);
                    returns.Where(p => p.Name.ToLower().Equals("uid")).FirstOrDefault().Value        = m.Uid;
                    //returns.Where(p => p.Name.ToLower().Equals("rawmessage")).FirstOrDefault().Value = m.RawBody;
                    //returns.Where(p => p.Name.ToLower().Equals("base64emlmessage")).FirstOrDefault().Value = m.Base64Body;
                    returns.Where(p => p.Name.ToLower().Equals("attachmentscount")).FirstOrDefault().Value = m.Attachments != null ? m.Attachments.Count : 0;

                    returns.Where(p => p.Name.ToLower().Equals("mailbox")).FirstOrDefault().Value       = mailbox;
                    returns.Where(p => p.Name.ToLower().Equals("uid")).FirstOrDefault().Value           = uid;
                    returns.Where(p => p.Name.ToLower().Equals("subjectfilter")).FirstOrDefault().Value = subjectfilter;

                    ic.Disconnect();
                }
            }
            catch (Exception ex)
            {
                //serviceObject.Properties.BindPropertiesToResultTable();
            }
            serviceObject.Properties.BindPropertiesToResultTable();
        }
コード例 #45
0
ファイル: ImapClient.cs プロジェクト: Comp-Ex/aenetmail
        public virtual void AppendMail(MailMessage email, string mailbox = null)
        {
            IdlePause();

            mailbox = ModifiedUtf7Encoding.Encode(mailbox);
            string flags = String.Empty;
            var body = new StringBuilder();
            using (var txt = new System.IO.StringWriter(body))
                email.Save(txt);

            string size = body.Length.ToString();
            if (email.RawFlags.Length > 0) {
                flags = " (" + string.Join(" ", email.Flags) + ")";
            }

            if (mailbox == null)
                CheckMailboxSelected();
            mailbox = mailbox ?? _SelectedMailbox;

            string command = GetTag() + "APPEND " + (mailbox ?? _SelectedMailbox).QuoteString() + flags + " {" + size + "}";
            string response = SendCommandGetResponse(command);
            if (response.StartsWith("+")) {
                response = SendCommandGetResponse(body.ToString());
            }
            IdleResume();
        }
コード例 #46
0
ファイル: ImapClient.cs プロジェクト: seanwm/aenetmail
        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();
        }
コード例 #47
0
        public void correos2()
        {
            ImapClient ic = new ImapClient();
            List <AE.Net.Mail.MailMessage> mx;
            List <AE.Net.Mail.MailMessage> emRq17;
            APPSETTING lg = db.APPSETTINGs.Where(x => x.NOMBRE == "logPath" && x.ACTIVO).FirstOrDefault();

            log.ruta = lg.VALUE + "LeerCorreos_";
            log.escribeLog("-----------------------------------------------------------------------START");
            try
            {
                List <CONMAIL> cc      = db.CONMAILs.ToList();
                CONMAIL        conmail = cc.FirstOrDefault(x => x.ID == "LE");
                if (conmail == null)
                {
                    log.escribeLog("Falta configurar inbox."); return;
                }
                ic = new ImapClient(conmail.HOST, conmail.MAIL, conmail.PASS,
                                    AuthMethods.Login, (int)conmail.PORT, conmail.SSL);

                // Select a mailbox. Case-insensitive
                ic.SelectMailbox("INBOX");

                //Esto traera los emails recibidos y no leidos
                //mx = ic.GetMessages(0, ic.GetMessageCount() - 1, true, false)
                long a = ic.GetMessageCount();
                if (a > 100)
                {
                    mx = ic.GetMessages(ic.GetMessageCount() - 100, ic.GetMessageCount() - 1, true, false)
                         .Where(m => !m.Flags.HasFlag(Flags.Seen) && !m.Flags.HasFlag(Flags.Deleted)).ToList();
                }
                else
                {
                    mx = ic.GetMessages(0, ic.GetMessageCount() - 1, true, false)
                         .Where(m => !m.Flags.HasFlag(Flags.Seen) && !m.Flags.HasFlag(Flags.Deleted)).ToList();
                }

                //En esta lista ingresaremos a los mails que sean recibidos como cc
                emRq17 = new List <AE.Net.Mail.MailMessage>();
                log.escribeLog("Leer inbox - numReg=(" + mx.Count + ")");
            }
            catch (Exception e)
            {
                mx     = new List <AE.Net.Mail.MailMessage>();
                emRq17 = new List <AE.Net.Mail.MailMessage>();
                log.escribeLog("Error al leer" + e.Message.ToString());
            }
            try
            {
                //ingresamos los correos CORREO
                for (int i = 0; i < mx.Count; i++)
                {
                    AE.Net.Mail.MailMessage mm = ic.GetMessage(mx[i].Uid, false);
                    try
                    {
                        string[] arrAsunto = mm.Subject.Split(']');
                        int      a         = arrAsunto.Length - 1;
                        //Recupero el asunto y lo separo del numdoc y pos
                        string[] arrAprNum = arrAsunto[a].Split('-');//RSG cambiar 0 a 1
                        string[] arrClaves = arrAprNum[1].Split('.');
                        //Valido que tenga los datos necesarios para el req 17
                        if (arrClaves.Length > 1)
                        {
                            arrClaves[1] = Decimal.Parse(arrClaves[1]).ToString();
                        }
                        ////var xy = arrAprNum[0].Trim();
                        if (arrAprNum[0].Trim() == "De Acuerdo" || arrAprNum[0].Trim() == "DeAcuerdo")
                        {
                            emRq17.Add(mm);
                            log.escribeLog("NEGO A - " + arrClaves[1]);
                        }
                        else if (arrAprNum[0].Trim() == "Tengo Observaciones" || arrAprNum[0].Trim() == "TengoObservaciones")
                        {
                            emRq17.Add(mm);
                            log.escribeLog("NEGO O - " + arrClaves[1]);
                        }
                    }
                    catch
                    {
                        ic.AddFlags(Flags.Seen, mm);
                        log.escribeLog("ERROR - " + mm.Subject);
                    }
                }
                //Correos de FLUJO DE APROBACIÓN y RECURRENTE-----------------------------------------------------2 y 3
                if (true)
                {
                    for (int i = 0; i < mx.Count; i++)
                    {
                        AE.Net.Mail.MailMessage mm = ic.GetMessage(mx[i].Uid, false);
                        try
                        {
                            string[] arrAsunto = mm.Subject.Split(']');
                            int      a         = arrAsunto.Length - 1;
                            //Recupero el asunto y lo separo del numdoc y pos
                            string[] arrAprNum = arrAsunto[a].Split('-');//RSG cambiar 0 a 1
                            string[] arrClaves = arrAprNum[1].Split('.');
                            decimal  numdoc    = Decimal.Parse(arrClaves[0]);
                            //Si el Texto es Aprobado, Rechazado o Recurrente
                            string[] arrApr = arrAprNum[0].Split(':');
                            if (arrApr.Length > 1)
                            {
                                ProcesaFlujo pF = new ProcesaFlujo();
                                if (arrApr[1] == "Approved" || arrApr[1] == "Rejected")
                                {
                                    log.escribeLog("APPR AR - " + arrClaves[0]);
                                    int   pos = Convert.ToInt32(arrAprNum[2]);
                                    FLUJO fl  = db.FLUJOes.Where(x => x.NUM_DOC == numdoc && x.POS == pos).FirstOrDefault();
                                    if (fl != null)
                                    {
                                        Console.WriteLine(mm.From.Address.Trim()); Console.WriteLine(fl.USUARIO.EMAIL);
                                        log.escribeLog("APPR mails - " + mm.From.Address.Trim() + " == " + fl.USUARIO.EMAIL);
                                        if (mm.From.Address.Trim().ToLower() == fl.USUARIO.EMAIL.Trim().ToLower() || mm.From.Address.Trim().ToLower() == fl.USUARIO1.EMAIL.Trim().ToLower())
                                        {
                                            Console.WriteLine("true");
                                            fl.ESTATUS = arrApr[1].Substring(0, 1);
                                            fl.FECHAM  = DateTime.Now;
                                            Comentario com = new Comentario();
                                            fl.COMENTARIO = com.getComment(mm.Body, mm.ContentType);
                                            ////fl.COMENTARIO = mm.Body;
                                            ////if (fl.COMENTARIO.Length > 255)
                                            ////    fl.COMENTARIO = fl.COMENTARIO.Substring(0, 252) + "...";
                                            var res = pF.procesa(fl, "");
                                            log.escribeLog("APPR PROCESA - Res = " + res);
                                            Email email = new Email();
                                            if (res == "1")
                                            {
                                                email.enviarCorreo(fl.NUM_DOC, 1, pos);
                                            }
                                            else if (res == "3")
                                            {
                                                email.enviarCorreo(fl.NUM_DOC, 3, pos);
                                            }

                                            using (TAT001Entities db1 = new TAT001Entities())
                                            {
                                                FLUJO     ff   = db1.FLUJOes.Where(x => x.NUM_DOC == fl.NUM_DOC).OrderByDescending(x => x.POS).FirstOrDefault();
                                                Estatus   es   = new Estatus();//RSG 18.09.2018
                                                DOCUMENTO ddoc = db1.DOCUMENTOes.Find(fl.NUM_DOC);
                                                ff.STATUS           = es.getEstatus(ddoc);
                                                db1.Entry(ff).State = System.Data.Entity.EntityState.Modified;
                                                db1.SaveChanges();
                                            }
                                            Console.WriteLine(res);
                                        }
                                    }
                                    ic.AddFlags(Flags.Seen, mm);
                                }
                                ////else if (arrApr[1] == "Rejected")
                                ////{
                                ////    int pos = Convert.ToInt32(arrAprNum[2]);
                                ////    FLUJO fl = db.FLUJOes.Where(x => x.NUM_DOC == numdoc && x.POS == pos).FirstOrDefault();
                                ////    fl.ESTATUS = "R";
                                ////    fl.FECHAM = DateTime.Now;
                                ////    fl.COMENTARIO = mm.Body;
                                ////    var res = pF.procesa(fl, "");
                                ////    if (res == "0")
                                ////    {
                                ////        //
                                ////    }
                                ////    else if (res == "1")
                                ////    {
                                ////        enviarCorreo(fl.NUM_DOC, 1);
                                ////    }
                                ////    else if (res == "3")
                                ////    {
                                ////        enviarCorreo(fl.NUM_DOC, 3);
                                ////    }
                                ////    //para marcar el mensaje como leido
                                ////    ic.AddFlags(Flags.Seen, mm);
                                ////}
                                else if (arrApr[1] == "Recurrent")
                                {
                                    ////Reversa r = new Reversa();
                                    ////string ts = db.DOCUMENTOes.Find(numdoc).TSOL.TSOLR;
                                    ////int ret = 0;
                                    ////if (ts != null)
                                    ////    ret = r.creaReversa(numdoc.ToString(), ts);

                                    //////para marcar el mensaje como leido
                                    ////if (ret != 0)
                                    ////    ic.AddFlags(Flags.Seen, mm);
                                }
                            }
                        }
                        catch (Exception ee)
                        {
                            ic.AddFlags(Flags.Seen, mm);
                            log.escribeLog("ERROR - " + ee.Message.ToString());
                        }
                    }
                }
                //req17
                ////FLUJNEGO fn = new FLUJNEGO();
                for (int i = 0; i < emRq17.Count; i++)
                {
                    ////AE.Net.Mail.MailMessage mm = emRq17[i];
                    AE.Net.Mail.MailMessage mm = ic.GetMessage(emRq17[i].Uid, false);
                    if (true)
                    {
                        string[] arrAsunto = mm.Subject.Split(']');
                        int      isa       = arrAsunto.Length - 1;
                        //Recupero el asunto y lo separo del numdoc y pos
                        string[] arrAprNum = arrAsunto[isa].Split('-');
                        string[] arrPiNN   = arrAprNum[1].Split('.');
                        var      _id       = int.Parse(arrPiNN[1]);
                        var      vkorg     = arrPiNN[2];
                        var      _correo   = arrPiNN[4].Replace('*', '.').Replace('+', '-').Replace('/', '@').Replace('#', '-');
                        //recupero las fechas de envio
                        var _xres = db.NEGOCIACIONs.Where(x => x.ID == _id).FirstOrDefault();
                        var pid   = arrPiNN[0];
                        //// var fs = db.DOCUMENTOes.Where(f => f.PAYER_ID == pid && f.FECHAC.Value.Month == DateTime.Now.Month  && f.FECHAC.Value.Year == DateTime.Now.Year && f.DOCUMENTO_REF == null).ToList();
                        var _xff = _xres.FECHAF.AddDays(1);
                        var fs   = db.DOCUMENTOes.Where(f => f.PAYER_ID == pid && f.VKORG == vkorg && f.PAYER_EMAIL == _correo && f.FECHAC >= _xres.FECHAI && f.FECHAC < _xff && f.DOCUMENTO_REF == null).ToList();
                        //LEJ 20.07.2018-----
                        var dOCUMENTOes = fs;
                        var lstD        = new List <DOCUMENTO>();//---
                        ////DOCUMENTOA dz = null;//---
                        for (int y = 0; y < dOCUMENTOes.Count; y++)
                        {
                            PorEnviar pe = new PorEnviar();
                            if (pe.seEnvia(dOCUMENTOes[y], db, log))
                            {
                                lstD.Add(dOCUMENTOes[y]);
                            }

                            //////recupero el numdoc
                            ////var de = fs[i].NUM_DOC;
                            //////sino ecuentra una coincidencia con el criterio discriminatorio se agregan o no a la lista
                            ////dz = db.DOCUMENTOAs.Where(x => x.NUM_DOC == de && x.CLASE != "OTR").FirstOrDefault();
                            ////if (dz == null || dz != null)
                            ////{
                            ////    if (dOCUMENTOes[y].TSOL.NEGO == true)//para el ultimo filtro
                            ////    {

                            ////        string estatus = "";
                            ////        if (dOCUMENTOes[y].ESTATUS != null) { estatus += dOCUMENTOes[y].ESTATUS; } else { estatus += " "; }
                            ////        if (dOCUMENTOes[y].ESTATUS_C != null) { estatus += dOCUMENTOes[y].ESTATUS_C; } else { estatus += " "; }
                            ////        if (dOCUMENTOes[y].ESTATUS_SAP != null) { estatus += dOCUMENTOes[y].ESTATUS_SAP; } else { estatus += " "; }
                            ////        if (dOCUMENTOes[y].ESTATUS_WF != null) { estatus += dOCUMENTOes[y].ESTATUS_WF; } else { estatus += " "; }
                            ////        if (dOCUMENTOes[y].FLUJOes.Count > 0)
                            ////        {
                            ////            estatus += dOCUMENTOes[y].FLUJOes.OrderByDescending(a => a.POS).FirstOrDefault().WORKFP.ACCION.TIPO;
                            ////        }
                            ////        else
                            ////        {
                            ////            estatus += " ";
                            ////        }
                            ////        if (dOCUMENTOes[y].TSOL.PADRE) { estatus += "P"; } else { estatus += " "; }
                            ////        if (dOCUMENTOes[y].FLUJOes.Where(x => x.ESTATUS == "R").ToList().Count > 0)
                            ////        {
                            ////            estatus += dOCUMENTOes[y].FLUJOes.Where(x => x.ESTATUS == "R").OrderByDescending(a => a.POS).FirstOrDefault().USUARIO.PUESTO_ID;
                            ////        }
                            ////        else
                            ////        {
                            ////            estatus += " ";
                            ////        }


                            ////        if (System.Text.RegularExpressions.Regex.IsMatch(estatus, "...[P][R].."))
                            ////            lstD.Add(dOCUMENTOes[y]);
                            ////        else if (System.Text.RegularExpressions.Regex.IsMatch(estatus, "...[R]..[8]"))
                            ////            lstD.Add(dOCUMENTOes[y]);
                            ////        else if (System.Text.RegularExpressions.Regex.IsMatch(estatus, "[P]..[A]..."))
                            ////            lstD.Add(dOCUMENTOes[y]);
                            ////        else if (System.Text.RegularExpressions.Regex.IsMatch(estatus, "..[P][A]..."))
                            ////            lstD.Add(dOCUMENTOes[y]);
                            ////        else if (System.Text.RegularExpressions.Regex.IsMatch(estatus, "..[E][A]..."))
                            ////            lstD.Add(dOCUMENTOes[y]);
                            ////        else if (System.Text.RegularExpressions.Regex.IsMatch(estatus, "...[A].[P]."))
                            ////            lstD.Add(dOCUMENTOes[y]);
                            ////        else if (System.Text.RegularExpressions.Regex.IsMatch(estatus, "...[A]..."))
                            ////            lstD.Add(dOCUMENTOes[y]);
                            ////        else if (System.Text.RegularExpressions.Regex.IsMatch(estatus, "...[T]..."))
                            ////            lstD.Add(dOCUMENTOes[y]);

                            ////        //if (dOCUMENTOes[y].ESTATUS_WF == "P")//LEJ 20.07.2018---------------------------I
                            ////        //{
                            ////        //    if (dOCUMENTOes[y].FLUJOes.Count > 0)
                            ////        //    {
                            ////        //        if (dOCUMENTOes[y].FLUJOes.OrderByDescending(a => a.POS).FirstOrDefault().USUARIO != null)
                            ////        //        {
                            ////        //            //(Pendiente Validación TS)
                            ////        //            if (dOCUMENTOes[y].FLUJOes.OrderByDescending(a => a.POS).FirstOrDefault().USUARIO.PUESTO_ID == 8)
                            ////        //            {
                            ////        //                lstD.Add(dOCUMENTOes[y]);
                            ////        //            }
                            ////        //        }
                            ////        //    }
                            ////        //}
                            ////        //else if (dOCUMENTOes[y].ESTATUS_WF == "R")//(Pendiente Corrección)
                            ////        //{
                            ////        //    if (dOCUMENTOes[y].FLUJOes.Count > 0)
                            ////        //    {
                            ////        //        lstD.Add(dOCUMENTOes[y]);
                            ////        //    }
                            ////        //}
                            ////        //else if (dOCUMENTOes[y].ESTATUS_WF == "T")//(Pendiente Taxeo)
                            ////        //{
                            ////        //    if (dOCUMENTOes[y].TSOL_ID == "NCIA")
                            ////        //    {
                            ////        //        if (dOCUMENTOes[y].PAIS_ID == "CO")//(sólo Colombia)
                            ////        //        {
                            ////        //            lstD.Add(dOCUMENTOes[y]);
                            ////        //        }
                            ////        //    }
                            ////        //}
                            ////        //else if (dOCUMENTOes[y].ESTATUS_WF == "A")//(Por Contabilizar)
                            ////        //{
                            ////        //    if (dOCUMENTOes[y].ESTATUS == "P")
                            ////        //    {
                            ////        //        lstD.Add(dOCUMENTOes[y]);
                            ////        //    }
                            ////        //}
                            ////        //else if (dOCUMENTOes[y].ESTATUS_SAP == "E")//Error en SAP
                            ////        //{
                            ////        //    lstD.Add(dOCUMENTOes[y]);
                            ////        //}
                            ////        //else if (dOCUMENTOes[y].ESTATUS_SAP == "X")//Succes en SAP
                            ////        //{
                            ////        //    lstD.Add(dOCUMENTOes[y]);
                            ////        //}
                            ////    }
                            ////    //LEJ 20.07.2018----------------------------------------------------------------T
                            ////}
                        }
                        //----
                        if (arrAprNum[0].Trim() == "DeAcuerdo" || arrAprNum[0].Trim() == "De Acuerdo")
                        {
                            for (int x = 0; x < lstD.Count; x++)
                            {
                                FLUJNEGO fn = new FLUJNEGO();
                                fn.NUM_DOC = lstD[x].NUM_DOC;
                                DateTime fecham = mm.Date;
                                fn.FECHAM = fecham;
                                fn.FECHAC = lstD[x].FECHAC;
                                fn.KUNNR  = arrPiNN[0];
                                var        cm  = arrAprNum[0].ToString();
                                Comentario com = new Comentario();
                                cm += com.getComment(mm.Body, mm.ContentType);
                                ////cm += " - " + mm.Body;
                                var cpos = db.FLUJNEGOes.Where(h => h.NUM_DOC.Equals(fn.NUM_DOC)).ToList().Count;
                                fn.POS        = cpos + 1;
                                fn.COMENTARIO = cm;
                                db.FLUJNEGOes.Add(fn);
                                db.SaveChanges();
                            }
                        }
                        else if (arrAprNum[0].Trim() == "TengoObservaciones" || arrAprNum[0].Trim() == "Tengo Observaciones")
                        {
                            for (int x = 0; x < lstD.Count; x++)
                            {
                                FLUJNEGO fn = new FLUJNEGO();
                                fn.NUM_DOC = lstD[x].NUM_DOC;
                                fn.FECHAC  = lstD[x].FECHAC;
                                DateTime fecham = mm.Date;
                                fn.FECHAM = fecham;
                                fn.KUNNR  = arrPiNN[0];
                                var        cm  = arrAprNum[0] + " ";
                                Comentario com = new Comentario();
                                cm += com.getComment(mm.Body, mm.ContentType);
                                ////cm += " - " + mm.Body;
                                var cpos = db.FLUJNEGOes.Where(h => h.NUM_DOC.Equals(fn.NUM_DOC)).ToList().Count;
                                fn.POS        = cpos + 1;
                                fn.COMENTARIO = cm;
                                db.FLUJNEGOes.Add(fn);
                                db.SaveChanges();
                            }
                        }
                        else
                        {
                            //Hubo algun error
                            break;
                        }
                    }
                    //para marcar el mensaje como leido
                    ic.AddFlags(Flags.Seen, mm);
                }
            }
            catch (Exception ex)
            {
                log.escribeLog("ERROR - " + ex.InnerException.ToString());
                ////throw new Exception(ex.InnerException.ToString());
            }
            finally
            {
                ic.Dispose();
            }
        }
コード例 #48
0
ファイル: ImapClient.cs プロジェクト: piher/aenetmail
        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();
        }
コード例 #49
0
ファイル: LinkExtractor.cs プロジェクト: rix0rrr/SiouxTube
 /// <summary>
 /// Return a plain text version of the message
 /// </summary>
 private string MessageAsText(MailMessage m)
 {
     return m.Subject + Environment.NewLine + m.Body +
         string.Join(Environment.NewLine, m.Attachments.Where(_ => _.ContentType == "text/plain").Select(_ => _.Body));
 }
コード例 #50
0
ファイル: TextClient.cs プロジェクト: harold4/aenetmail
 protected virtual void RaiseWarning(MailMessage mailMessage, string message)
 {
     var warning = Warning;
     if (warning != null) {
         warning(this, new WarningEventArgs { MailMessage = mailMessage, Message = message });
     }
 }
コード例 #51
-1
ファイル: Pop3Client.cs プロジェクト: mbithy/aenetmail
		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;
		}
コード例 #52
-1
ファイル: ImapClient.cs プロジェクト: kareem613/aenetmail
        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();
        }