Пример #1
0
        /// <summary>
        ///      SentSince = Date  = DateFrom
        ///      SentBefore = Date + 1 = DateTO
        /// </summary>
        /// <returns></returns>
        public SearchCondition SetSearchConditions()
        {
            SearchCondition result = SearchCondition.All();

            if (this.SearchByDateRange)
            {
                result = result.And(SearchCondition.SentBefore(new DateTime(DateTo.Year, DateTo.Month, DateTo.Day).AddDays(1))
                                    .And(SearchCondition.SentSince(new DateTime(DateFrom.Year, DateFrom.Month, DateFrom.Day))));
            }
            if (this.Unread)
            {
                result = result.And(SearchCondition.Unseen());
            }
            if (!string.IsNullOrEmpty(this.Sender))
            {
                result = result.And(SearchCondition.From(this.Sender));
            }
            if (!string.IsNullOrEmpty(this.Subject))
            {
                result = result.And(SearchCondition.Subject(this.Subject));
            }



            return(result);
        }
Пример #2
0
        private void btn_SearchMessage_Click(object sender, EventArgs e)
        {
            ImapClient         client = new ImapClient("imap.gmail.com", 993, txt_Email.Text, txt_Password.Text, AuthMethod.Auto, true);
            IEnumerable <uint> uids   = client.Search(SearchCondition.From(txt_Dest_Email.Text));

            listBox1.Items.Clear();
            listBox1.Items.Add("Message ID's which mail is from" + " ' " + txt_Dest_Email.Text + " ' ");
            foreach (var item in uids)
            {
                listBox1.Items.Add(item);
            }
        }
        public IEnumerable <MailMessage> GetMessages(string pattern)
        {
            string     searchPattern = @"*" + pattern + @"*";
            ImapClient client        = new ImapClient(hostname, 993, Username, Password, AuthMethod.Login, true);
            IEnumerable <MailMessage> messages;

            using (client)
            {
                IEnumerable <uint> uids = client.Search(SearchCondition.From(searchPattern).Or(SearchCondition.Subject(searchPattern).Or(SearchCondition.Body(searchPattern))));
                messages = client.GetMessages(uids.ToArray());
            }
            return(messages);
        }
Пример #4
0
        private static void FindMessageBySubject()
        {
            ImapClient client = ConnectIMAP(ToAddress, Password);
            // Find messages that were sent from [email protected] and have the string "Hello World" in their subject line.
            IEnumerable <uint> uids = client.Search(SearchCondition.Unseen().And(SearchCondition.From(FromAddress)).And(SearchCondition.Subject(Subject)));

            if (uids.Count() != 1)
            {
                throw new Exception($"Find {uids.Count()} messages matchs address: {FromAddress}, subject:{Subject}");
            }

            Console.WriteLine("Find message by subject successfully!");
        }
        public IEnumerable <MailMessage> GetSearchedMessages(string pattern)
        {
            IEnumerable <MailMessage> messages;
            ImapClient client = GetClient();

            using (client)
            {
                IEnumerable <uint> uids = client.Search(SearchCondition.From(pattern).Or(
                                                            SearchCondition.Subject(pattern)));
                messages = client.GetMessages(uids);
            }
            return(messages);
        }
Пример #6
0
        public MailMessage GetLastEmail(string username, string password = "******")
        {
            using (var imap = new ImapClient("imap.gmail.com", username, password, port: 993, secure: true, skipSslValidation: true))
            {
                var msgs = imap.SearchMessages(
                    SearchCondition.Unseen().And(
                        SearchCondition.From("*****@*****.**"),
                        SearchCondition.SentSince(DateTime.Now.Subtract(TimeSpan.FromMinutes(20)))
                        ));

                return(msgs.Length > 0 ? msgs[0].Value : null);
            }
        }
Пример #7
0
        public void Delete_Message()
        {
            using (var client = GetClient <ImapClient>()) {
                var lazymsg = client.SearchMessages(SearchCondition.From("DRAGONEXT")).FirstOrDefault();
                var msg = lazymsg == null ? null : lazymsg.Value;
                msg.Should().Not.Be.Null();

                var uid = msg.Uid;
                client.DeleteMessage(msg);

                msg = client.GetMessage(uid);
                Console.WriteLine(msg);
            }
        }
Пример #8
0
        public void MarkAllAsSeen(string username, string password = "******")
        {
            using (var imap = new ImapClient("imap.gmail.com", username, password, port: 993, secure: true, skipSslValidation: true))
            {
                var msgs = imap.SearchMessages(
                    SearchCondition.Unseen().And(
                        SearchCondition.From("*****@*****.**")
                        ));

                foreach (var msg in msgs)
                {
                    imap.SetFlags(Flags.Seen, msg.Value);
                }
            }
        }
Пример #9
0
        public void TestSearch()
        {
            using (var imap = GetClient <ImapClient>()) {
                var result = imap.Search(
                    //"OR ((UNDELETED) (FROM \"david\") (SENTSINCE \"01-Jan-2000 00:00:00\")) (TO \"andy\")"
                    SearchCondition.Undeleted().And(SearchCondition.From("david"), SearchCondition.SentSince(new DateTime(2000, 1, 1))).Or(SearchCondition.To("andy"))
                    );
                result.Length.Should().Be.InRange(1, int.MaxValue);

                result = imap.Search(new SearchCondition {
                    Field = SearchCondition.Fields.Text, Value = "asdflkjhdlki2uhiluha829hgas"
                });
                result.Length.Should().Equal(0);
            }
        }
Пример #10
0
        public static void BackupImap()
        {
            string uzisRoot = Program.GetExecutingDirectoryName() + "\\UZIS_Reports\\";

            string obsazenostFile = null;

            using (ImapClient Client = new ImapClient("imap.gmail.com", 993,
                                                      "", "", AuthMethod.Login, true))
            {
                // This returns all messages sent since August 23rd 2012.
                IEnumerable <uint> uids = Client.Search(
                    SearchCondition.From("*****@*****.**")
                    .And(SearchCondition.To("*****@*****.**"))
                    //SearchCondition.All()
                    );


                // The expression will be evaluated for every MIME part
                // of every mail message in the uids collection.
                foreach (var uid in uids)
                {
                    Console.WriteLine(uid);
                    var msg = Client.GetMessage(uid);
                    Console.Write($" {msg.Date()} ");

                    string reportDir = uzisRoot + msg.Date()?.ToString("yyyy-MM-dd") + "\\";
                    if (System.IO.Directory.Exists(reportDir) == false)
                    {
                        System.IO.Directory.CreateDirectory(reportDir);
                    }

                    foreach (var att in msg.Attachments)
                    {
                        Console.Write(".");
                        if (att.ContentDisposition.Inline == false)
                        {
                            using (var fs = System.IO.File.Create(reportDir + MakeValidFileName(att.Name)))
                            {
                                att.ContentStream.Seek(0, System.IO.SeekOrigin.Begin);
                                att.ContentStream.CopyTo(fs);
                            }
                        }
                    }
                    Console.WriteLine();
                }
            }
        }
Пример #11
0
        public async Task <string> getImageFrom(string from, int index = 0)
        {
            // Connect to the IMAP server. The 'true' parameter specifies to use SSL
            // which is important (for Gmail at least)
            ImapClient ic = new ImapClient("imap.gmail.com", "*****@*****.**", "20201999", AuthMethods.Login, 993, true);

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

            var mm = ic.SearchMessages(SearchCondition.From(from));

            MailMessage msg   = mm[Math.Abs((mm.Length - index - 1) % mm.Length)].Value;
            string      image = msg.Attachments.ElementAt(0).Body;

            // Probably wiser to use a using statement
            ic.Dispose();

            return(image);
        }
Пример #12
0
        public void Search_Conditions_Operators()
        {
            var deleted = SearchCondition.Deleted();
            var seen    = SearchCondition.Seen();
            var text    = SearchCondition.Text("andy");

            deleted.ToString().ShouldBe("DELETED");
            (deleted | seen).ToString().ShouldBe("OR (DELETED) (SEEN)");
            (seen & text).ToString().ShouldBe("(SEEN) (TEXT \"andy\")");

            var since = new DateTime(2000, 1, 1);

            ((SearchCondition.Undeleted()
              & SearchCondition.From("david")
              & SearchCondition.SentSince(since)
              ) | SearchCondition.To("andy"))
            .ToString()
            .ShouldBe("OR ((UNDELETED) (FROM \"david\") (SENTSINCE \"" + Utilities.GetRFC2060Date(since) + "\")) (TO \"andy\")");
        }
Пример #13
0
        public void Search_Conditions()
        {
            var deleted = SearchCondition.Deleted();
            var seen    = SearchCondition.Seen();
            var text    = SearchCondition.Text("andy");

            deleted.ToString().Should().Equal("DELETED");
            deleted.Or(seen).ToString().Should().Equal("OR (DELETED) (SEEN)");
            seen.And(text).ToString().Should().Equal("(SEEN) (TEXT \"andy\")");

            var since = new DateTime(2000, 1, 1);

            SearchCondition.Undeleted().And(
                SearchCondition.From("david"),
                SearchCondition.SentSince(since)
                ).Or(SearchCondition.To("andy"))
            .ToString()
            .Should().Equal("OR ((UNDELETED) (FROM \"david\") (SENTSINCE \"" + Utilities.GetRFC2060Date(since) + "\")) (TO \"andy\")");
        }
Пример #14
0
        public void SearchConditions()
        {
            var dict = new Dictionary <string, SearchCondition>()
            {
                { "(From \"[email protected]\") (Larger 1024)",
                  SearchCondition.From("*****@*****.**").And(SearchCondition.Larger(1024)) },
                { "Or (Unanswered) (Flagged)",
                  SearchCondition.Unanswered().Or(SearchCondition.Flagged()) },
                { "Or ((Subject {12}\r\n重要郵件) (SentBefore \"20-Dec-2012\")) (Unseen)",
                  SearchCondition.Subject("重要郵件").And(SearchCondition
                                                      .SentBefore(new DateTime(2012, 12, 20))).Or(SearchCondition.Unseen()) }
            };

            foreach (KeyValuePair <string, SearchCondition> p in dict)
            {
                Assert.IsTrue(p.Key.Equals(p.Value.ToString(),
                                           StringComparison.InvariantCultureIgnoreCase));
            }
        }
Пример #15
0
 void listofMessages()
 {
     foreach (var i in imapClient.Search(
                  SearchCondition.From(mailMessages.From).Or(SearchCondition.Subject(mailMessages.SearchCriterion))))
     {
         var messages = imapClient.GetMessage(i,
                                              FetchOptions.Normal, true, null);
         if (this.InvokeRequired)
         {
             this.Invoke(new Action(() =>
             {
                 dataGridView1.Rows.Add(new object[] { i, messages.Subject.ToString(), messages.Date(), "Print" });
             }));
         }
         else
         {
             dataGridView1.Rows.Add(new object[] { i, messages.Subject.ToString(), messages.Date(), "Print" });
         }
     }
 }
Пример #16
0
        public static List <MailMessage> SearchMessages(MailObj mObj, string searchFrom, string searchSubject, string searchText, string searchKeyword)
        {
            using (ImapClient Client = new ImapClient(mObj.ServerAddress, mObj.Port, mObj.MailAddress, mObj.MailAddressPassword, AuthMethod.Login, true))
            {
                List <SearchCondition> scList = new List <SearchCondition>();

                if (!string.IsNullOrWhiteSpace(searchFrom))
                {
                    scList.Add(SearchCondition.From(searchFrom));
                }
                if (!string.IsNullOrWhiteSpace(searchSubject))
                {
                    scList.Add(SearchCondition.Subject(searchSubject));
                }
                if (!string.IsNullOrWhiteSpace(searchText))
                {
                    scList.Add(SearchCondition.Text(searchText));
                }
                if (!string.IsNullOrWhiteSpace(searchKeyword))
                {
                    scList.Add(SearchCondition.Keyword(searchKeyword));
                }


                if (scList.Count > 0)
                {
                    SearchCondition allConditions = scList[0];
                    for (int i = 1; i < scList.Count; i++)
                    {
                        allConditions.And(scList[i]);
                    }

                    IEnumerable <uint> uids = Client.Search(allConditions);
                    return(Client.GetMessages(uids).ToList());
                }

                return(new List <MailMessage>());
            }
        }
Пример #17
0
        /// <summary>
        /// Creates a <see cref="SearchCondition"/> object from a <see cref="EmailSearchCriteria"/>
        /// </summary>
        /// <param name="searchCriteria"></param>
        /// <returns></returns>
        private SearchCondition GetSearchCondition(EmailSearchCriteria searchCriteria)
        {
            var searchCondition = new SearchCondition();

            if (!string.IsNullOrWhiteSpace(searchCriteria.From))
            {
                searchCondition = searchCondition.And(SearchCondition.From(searchCriteria.From));
            }

            if (searchCriteria.After.HasValue)
            {
                searchCondition = searchCondition.And(SearchCondition.SentBefore(searchCriteria.After.Value));
            }

            if (searchCriteria.Since.HasValue)
            {
                searchCondition = searchCondition.And(SearchCondition.SentSince(searchCriteria.Since.Value));
            }

            if (searchCriteria.Unread.HasValue)
            {
                searchCondition = searchCondition.And(searchCriteria.Unread.Value ? SearchCondition.Unseen() : SearchCondition.Seen());
            }

            if (searchCriteria.SubjectKeywords != null && searchCriteria.SubjectKeywords.Any())
            {
                searchCondition = searchCondition.And(
                    searchCriteria.SubjectKeywords.Select(SearchCondition.Subject).Aggregate((sc1, sc2) => sc1.Or(sc2)));
            }

            if (searchCriteria.BodyKeywords != null && searchCriteria.BodyKeywords.Any())
            {
                searchCondition = searchCondition.And(
                    searchCriteria.BodyKeywords.Select(SearchCondition.Body).Aggregate((sc1, sc2) => sc1.Or(sc2)));
            }

            return(searchCondition);
        }
Пример #18
0
        public List <Email> GetMails()
        {
            List <Email> messages = new List <Email>();

            using (
                ImapClient client = Connection)
            {
                // This returns *ALL* messages in the inbox.
                IEnumerable <uint> uids =
                    client.Search(
                        SearchCondition.From("*****@*****.**").And(SearchCondition.Subject("Varefil fra C. Reinhardt A/S")));

                foreach (uint uid in uids)
                {
                    var mes = client.GetMessage(uid, FetchOptions.Normal, false);
                    messages.Add(new Email()
                    {
                        Key = uid, Message = mes
                    });
                }
            }

            return(messages);
        }
Пример #19
0
 public MailClient()
 {
     try
     {
         client.Login(Program.config["MailUsername"], Program.config["MailPassword"], AuthMethod.Auto);
     }
     catch { }
     if (!client.Authed)
     {
         Logger.Error(PREFIX + "Can't log in to mail server.");
         Program.Pause();
     }
     else
     {
         new Thread(new ThreadStart(() =>
         {
             while (true)
             {
                 try
                 {
                     var mails = client.Search(SearchCondition.Undeleted().And(SearchCondition.Unflagged()).And(SearchCondition.Unseen()).And(SearchCondition.From("*****@*****.**")));
                     foreach (uint id in mails)
                     {
                         processMessage(id);
                     }
                     Thread.Sleep(500);
                 }
                 catch
                 {
                     if (!client.Authed)
                     {
                         try
                         {
                             client.Login(Program.config["MailUsername"], Program.config["MailPassword"], AuthMethod.Auto);
                         }
                         catch { }
                     }
                 }
             }
         }))
         {
             IsBackground = true
         }.Start();
         Logger.Info(PREFIX + "Successfully logged in to mail server.");
     }
 }
Пример #20
0
        public async void test()
        {
            try
            {
                //todo: change credential
                using (ImapClient Client = new ImapClient("imap.gmail.com", 993,
                                                          "[ENTER gmail account]", "[ENTER gmail pass]", AuthMethod.Login, true))
                {
                    Console.WriteLine("We are connected!");

                    IEnumerable <uint> uids = Client.Search(SearchCondition.Unseen().And(SearchCondition.From("*****@*****.**")));


                    if (uids.Count() > 0)
                    {
                        IEnumerable <MailMessage> messages = Client.GetMessages(uids);

                        StringBuilder message = new StringBuilder();
                        message.AppendLine("```Markdown");
                        message.AppendLine("#Notisias freshcas");
                        message.AppendLine("```");

                        foreach (var mess in messages)
                        {
                            message.Append(mess.Body.Substring(mess.Body.IndexOf("=====") + 5, mess.Body.IndexOf("=====", 50) - mess.Body.IndexOf("=====") - 5).Replace("\r", "").Replace("\n", "").Replace("&#039", "'") + "\r");
                        }

                        var client = new DiscordClient();
                        //todo: change token
                        await client.Connect("[PON AKI TU TOKEN]", TokenType.Bot);
                        await SendMessage(client.GetChannel(289034769159946240), message.ToString());
                    }
                }
            }catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Пример #21
0
        public void InitCredential()
        {
            _searchCondition = new SearchCondition();

            SearchCondition condition = null;

            if (!string.IsNullOrEmpty(Senders))
            {
                List <string> mSenders = Senders.Split(';').ToList();
                condition = SearchCondition.From(mSenders[0]);
                for (int i = 1; i < mSenders.Count; i++)
                {
                    string sender = mSenders[i];
                    if (string.IsNullOrEmpty(sender))
                    {
                        continue;
                    }

                    condition = condition.Or(SearchCondition.From(sender));
                }
            }

            SearchCondition conditionSubject = null;

            if (!string.IsNullOrEmpty(Subjects))
            {
                List <string> mSubjects = Subjects.Split(';').ToList();
                conditionSubject = SearchCondition.Subject(mSubjects[0]);
                for (int i = 1; i < mSubjects.Count; i++)
                {
                    string sub = mSubjects[i];
                    if (string.IsNullOrEmpty(sub))
                    {
                        continue;
                    }

                    conditionSubject = conditionSubject.Or(SearchCondition.Subject(sub));
                }
            }

            _searchCondition = SearchCondition.Unseen();

            if (condition != null)
            {
                _searchCondition = _searchCondition.And(condition);
            }

            if (conditionSubject != null)
            {
                _searchCondition = _searchCondition.And(conditionSubject);
            }

            try
            {
                if (_email != null)
                {
                    _email.Logout();
                }
            }
            catch
            {
            }

            try
            {
                if (!string.IsNullOrEmpty(Credential.UserName) && !string.IsNullOrEmpty(Credential.Host))
                {
                    _email = new ImapClient(Credential.Host, Credential.Port, Credential.UserName, Credential.Password, AuthMethod.Login, Credential.Ssl);
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                throw ex;
            }
        }
Пример #22
0
        private string GetTwoFactorCodeInternal()
        {
            var code = "";

            try
            {
                using (var client = new ImapClient(_hostName, _port, Username, Password, AuthMethod.Auto, _useSsl, (sender, certificate, chain, errors) => true))
                {
                    List <uint> uids  = client.Search(SearchCondition.To(Username).And(SearchCondition.From("ea.com"))).ToList();
                    var         mails = client.GetMessages(uids, FetchOptions.Normal);

                    foreach (var msg in mails)
                    {
                        if (msg == null)
                        {
                            continue;
                        }
                        if (msg.From.Address.Contains("ea.com") && Regex.IsMatch(msg.Subject, "([0-9]+)") && ((DateTime)msg.Date()).ToUniversalTime() > _codeSent.ToUniversalTime())
                        {
                            var mailBody = msg.Subject;
                            code = Regex.Match(mailBody, "([0-9]+)").Groups[1].Value;
                            break;
                        }
                    }
                    if (uids.Count > 0)
                    {
                        client.DeleteMessages(uids);
                    }
                }
            }
#pragma warning disable CS0168
            catch (Exception e)
            {
                code = "EXC" + e;
            }
#pragma warning restore CS0168
            return(code);
        }
        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();
        }
Пример #24
0
 private void MailForm_Load(object sender, EventArgs e)
 {
     tryLogin();
     if (!client.Authed)
     {
         MessageBox.Show("Can't log in to mail server.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         Close();
     }
     else if (!client.Supports("IDLE"))
     {
         MessageBox.Show("Server doesn't support IDLE.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         Close();
     }
     else
     {
         client.IdleError += (s, ev) =>
         {
             Console.WriteLine(ev.Exception);
         };
         client.NewMessage += (s, ev) => processMessage(ev.MessageUID);
         new Thread(new ThreadStart(() =>
         {
             while (!IsDisposed)
             {
                 try
                 {
                     if (!client.Authed)
                     {
                         throw new Exception();
                     }
                     var mails = client.Search(SearchCondition.Undeleted().And(SearchCondition.Unseen()).And(SearchCondition.From("*****@*****.**")));
                     foreach (uint id in mails)
                     {
                         processMessage(id);
                     }
                 }
                 catch
                 {
                     tryLogin();
                     continue;
                 }
                 Thread.Sleep(1000);
             }
         }))
         {
             IsBackground = true
         }.Start();
     }
 }
Пример #25
0
 public List <MailModel> GetSentMessages()
 {
     return(GetMessages(SearchCondition.From(_user.Username))
            .OrderByDescending(m => m.Date)
            .ToList());
 }
        public void ReadEmails(string folder,
                               DateTime?fromDate,
                               IList <string> acceptingToAddresses,
                               IList <string> acceptingFromAddresses,
                               CancellationToken?cancel)
        {
            _emailProcessResultList = new List <EmailReadingResult>();

            using (var imap = new ImapClient(_settings.ImapHost,
                                             _settings.ImapPort,
                                             _settings.ImapUsername,
                                             _settings.ImapPassword,
                                             AuthMethod.Login,
                                             ssl: true))
            {
                //var uids = new List<uint>(ImapClient.Search(SearchCondition.SentSince(sentSince).Or(SearchCondition.GreaterThan(lastUid)), mailbox));

                //var uids = new List<uint>(ImapClient.Search(SearchCondition.From("*****@*****.**"), _mailbox));
                //var uids = new List<uint> {lastUid};// 14559 };
                //var uids = new List<uint>(ImapClient.Search(SearchCondition.SentSince(new DateTime(2013, 12, 3)).Or(SearchCondition.GreaterThan(105748)), mailbox));//.SentSince(sentSince.AddHours(-12)), mailbox));


                var sentSince = fromDate ?? _time.GetUtcTime().AddDays(-2);
                using (var db = _dbFactory.GetRWDb())
                {
                    DateTime?maxEmailDate = db.Emails.GetAll().Max(e => e.ReceiveDate);
                    if (maxEmailDate.HasValue)
                    {
                        sentSince = maxEmailDate.Value.AddHours(-5);
                    }
                }

                uint lastUid = 0;

                //_log.Info(String.Join("; ", imap.ListMailboxes()));
                //var uids = new List<uint>(imap.Search(SearchCondition.SentSince(sentSince).Or(SearchCondition.GreaterThan(lastUid)), "INBOX"));
                var uids = new List <uint>();
                if (_settings.IsDebug)
                {
                    uids = new List <uint>()
                    {
                        30456
                    };
                    //  imap.Search(SearchCondition.Subject("kimlimu_cecku3g5 sent a message about Peppa Pig Little Girls"), folder).ToList();}
                }
                else
                {
                    SearchCondition toCriteria = null;
                    if (acceptingToAddresses != null && acceptingToAddresses.Any())
                    {
                        foreach (var to in acceptingToAddresses)
                        {
                            toCriteria = toCriteria == null?SearchCondition.To(to) : toCriteria.Or(SearchCondition.To(to));
                        }
                    }

                    SearchCondition fromCriteria = null;
                    if (acceptingFromAddresses != null && acceptingFromAddresses.Any())
                    {
                        foreach (var from in acceptingFromAddresses)
                        {
                            fromCriteria = fromCriteria == null?SearchCondition.From(from) : fromCriteria.Or(SearchCondition.From(from));
                        }
                    }

                    var searchCriteria = SearchCondition.SentSince(sentSince);
                    if (toCriteria != null)
                    {
                        searchCriteria = searchCriteria.And(toCriteria);
                    }
                    if (fromCriteria != null)
                    {
                        searchCriteria = searchCriteria.And(fromCriteria);
                    }
                    uids = new List <uint>(imap.Search(searchCriteria, folder));
                }


                foreach (var uid in uids)
                {
                    if (cancel.HasValue && cancel.Value.IsCancellationRequested)
                    {
                        _log.Info("Cancellation Requested!");
                        cancel.Value.ThrowIfCancellationRequested();
                    }


                    _log.Info("Begin check uid: " + uid);
                    var emailProcessingThread = new Thread(() => GetEmail(_dbFactory, imap, _time.GetUtcTime(), uid, folder));
                    emailProcessingThread.Priority = ThreadPriority.Highest;
                    emailProcessingThread.Start();

                    if (_settings.IsDebug)
                    {
                        emailProcessingThread.Join();
                    }
                    else
                    {
                        if (!emailProcessingThread.Join(_settings.ProcessMessageThreadTimeout))
                        {
                            emailProcessingThread.Abort();
                            throw new Exception("Timeout exceeded while processing email. Uid:" + uid);
                        }
                    }
                }

                Console.WriteLine(uids.Count);
            }
        }
Пример #27
0
 static SearchCondition GetSearchCondition()
 {
     return(SearchCondition.From(readMessagesFilterAccount).And(SearchCondition.Unseen()));
 }
Пример #28
0
        public static List <DeliveryMessage> GetMessages(
            string username,
            string password,
            SearchCondition searchCondition = null
            )
        {
            List <DeliveryMessage> res = new List <DeliveryMessage>();
            MessageFinder          mf  = new MessageFinder(username, password);

            IEnumerable <MailMessage> messages = mf.GetMessagesBySearchCondition(searchCondition ?? SearchCondition.From("*****@*****.**").And(SearchCondition.Subject("subject")).And(SearchCondition.Unseen()));

            foreach (var msg in messages)
            {
                res.Add(new DeliveryMessage(msg));
            }

            return(res);
        }
Пример #29
0
        //ReadEmail is the handler for email based detectors. It is designed
        //to retrieve email from a configured email service and parse the alerts
        public static void ReadEmail(string sVendor, string sFolderName, string sFolderNameTest, string sDetectorEmail, bool isParamTest)
        {
            switch (sVendor)
            {
            //Outlook based email plugin which requires the Outlook client to be installed.
            case "outlook":
                #region Microsoft Outlook Plugin
                //try
                //{
                //  //Setup connection information to mailstore
                //  //If logon information is null then mailstore must be open already
                //  //var oApp = new Microsoft.Office.Interop.Outlook.Application();
                //  //var sFolder = new Microsoft.Office.Interop.Outlook.Folder(sFolderName);
                //  //var oNameSpace = oApp.GetNamespace("MAPI");
                //  //oNameSpace.Logon(null, null, true, true);
                //  //var oInboxFolder = oNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
                //  //Outlook.Folder oFolder = oInboxFolder.Folder[sFolderName];

                //  //logging
                //  //Logging_Fido.Main.RunLogging("Running FIDO on file " + sFolderName);

                //  ////attach to folder and for each item in the folder then loop. During loop assign subject, body and detect malware type
                //  //foreach (var item in sFolder.Items)
                //  //{
                //  //  var oMailItem = item as Microsoft.Office.Interop.Outlook._MailItem;
                //  //  if (oMailItem != null)
                //  //  {
                //  //    var sMessageBody = oMailItem.Body;
                //  //  }
                //  //  if (oMailItem != null)
                //  //  {
                //  //    var sSubject = oMailItem.Subject;
                //  //  }
                //    //List<string> sERet = scan_email(sSubject, sMessageBody, sFolderName);
                //  //  if (sERet.First() == "Test Email")
                //  //  {
                //  //    oMailItem.Delete();
                //  //  }
                //  //  else
                //  //  {
                //  //    fido.Form1.Run_FIDO(sMessageBody, sERet, "fubar", false, false, true, sVendor);//MalwareType
                //  //    oMailItem.Delete();
                //  //  }
                //  }
                #endregion

                //}
                //catch (Exception e)
                //{
                //  Fido_Modules.Fido.Fido_EventHandler.SendEmail("Fido Error", "Fido Failed: {0} Exception caught in Outlook emailreceive area:" + e);
                //}
                break;

            case "exchange":
                #region Microsoft Exchange Plugin
                //still need to build out direct Exchange access
                #endregion
                break;

            //IMAP based email plugin which has been verified to work with Gmail
            case "imap":
                #region IMAP Plugin
                try
                {
                    //get encrypted password and decrypt
                    //then login
                    var sfidoemail  = Object_Fido_Configs.GetAsString("fido.email.fidoemail", null);
                    var sfidopwd    = Object_Fido_Configs.GetAsString("fido.email.fidopwd", null);
                    var sfidoacek   = Object_Fido_Configs.GetAsString("fido.email.fidoacek", null);
                    var sImapServer = Object_Fido_Configs.GetAsString("fido.email.imapserver", null);
                    var iImapPort   = Object_Fido_Configs.GetAsInt("fido.email.imapport", 0);
                    sfidoacek = Aes_Crypto.DecryptStringAES(sfidoacek, "1");
                    sfidopwd  = Aes_Crypto.DecryptStringAES(sfidopwd, sfidoacek);
                    IImapClient gLogin = new ImapClient(sImapServer, iImapPort, sfidoemail, sfidopwd, AuthMethod.Login, true);

                    var sSeperator = new[] { "," };
                    gLogin.DefaultMailbox = isParamTest ? sFolderNameTest : sFolderName;
                    var listUids = new List <uint>();

                    //seperate out list of email addresses handed to emailreceive
                    //then run query based on each email from the specified folder
                    //and finally convert to array
                    string[] aryInboxSearch = sDetectorEmail.Split(sSeperator, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var search in aryInboxSearch)
                    {
                        listUids.AddRange(gLogin.Search(SearchCondition.From(search)).ToList());
                    }
                    var uids = listUids.ToArray();
                    uids = uids.Take(50).ToArray();
                    var msg          = gLogin.GetMessages(uids);
                    var mailMessages = msg as MailMessage[] ?? msg.ToArray();
                    for (var i = 0; i < mailMessages.Count(); i++)
                    {
                        var sMessageBody = mailMessages[i].Body;
                        var sSubject     = mailMessages[i].Subject;
                        var sERet        = ScanEmail(sSubject, sMessageBody, sFolderName, isParamTest);
                        if (sERet == "Test Email")
                        {
                            Console.WriteLine(@"Test email found, putting in processed folder.");
                            gLogin.MoveMessage(uids[i], "Processed");
                        }
                        else
                        {
                            Console.WriteLine(@"Finished processing email alert, puttig in processed folder.");
                            gLogin.MoveMessage(uids[i], "Processed");
                        }
                    }
                    #endregion
                }
                catch (Exception e)
                {
                    Fido_EventHandler.SendEmail("Fido Error", "Fido Failed: {0} Exception caught in IMAP emailreceive area:" + e);
                }
                Console.WriteLine(@"Finished processing email alerts.");
                break;
            }
        }