SelectMailbox() public method

public SelectMailbox ( string mailboxname ) : void
mailboxname string
return void
コード例 #1
0
 public static bool openNewImapClient()
 {
     try
     {
         if (UserData.checkIsGmailEmail())
         {
             mImapClient = new ImapClient(GMAIL_IMAP_SERVER, UserData.getEmailAddres(),
                                          UserData.getEmailPassword(), AE.Net.Mail.AuthMethods.Login, 993, true);
         }
         else
         {
             mImapClient = new ImapClient(MAIL_IMAP_SERVER, UserData.getEmailAddres(),
                                          UserData.getEmailPassword(), AE.Net.Mail.AuthMethods.Login, 993, true);
         }
         mImapClient.SelectMailbox(INBOX_MAILBOX);
         AE.Net.Mail.Imap.Mailbox[] mailBoxes = mImapClient.ListMailboxes(string.Empty, "*");
         foreach (var mailBox in mailBoxes)
         {
             var mailboxName = mailBox.Name;
         }
     }
     catch (Exception e)
     {
         return(false);
     }
     return(true);
 }
コード例 #2
0
        public static void Verify(string email, string pass, string ipmap, int port)
        {
            string url = null;

            using (ImapClient ic = new ImapClient())
            {
                ic.Connect(ipmap, port, true, false);
                ic.Login(email, pass);
                ic.SelectMailbox("INBOX");
                int mailcount;
                for (mailcount = ic.GetMessageCount(); mailcount < 2; mailcount = ic.GetMessageCount())
                {
                    Mail.Delay(5);
                    ic.SelectMailbox("INBOX");
                }
                MailMessage[] mm    = ic.GetMessages(mailcount - 1, mailcount - 1, false, false);
                MailMessage[] array = mm;
                for (int j = 0; j < array.Length; j++)
                {
                    MailMessage i = array[j];
                    //bool flag = i.Subject == "Account registration confirmation" || i.Subject.Contains("Please verify your account");
                    //if (flag)
                    {
                        string sbody = i.Body;
                        url = Regex.Match(i.Body, "a href=\"(https:[^\n]+)").Groups[1].Value;
                        bool flag2 = string.IsNullOrEmpty(url);
                        if (flag2)
                        {
                            url = Regex.Match(i.Body, "(http.*)").Groups[1].Value.Trim();
                            url = url.Substring(0, url.IndexOf('"'));
                        }
                        break;
                    }
                }
                ic.Dispose();
            }
            HttpRequest rq = new HttpRequest();

            rq.Cookies   = new CookieDictionary(false);
            rq.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36";
            bool Load = false;

            while (!Load)
            {
                try
                {
                    rq.Get(url, null);
                    Load = true;
                }
                catch (Exception)
                {
                }
            }
        }
コード例 #3
0
ファイル: Email.cs プロジェクト: tieuloitu1/NewProject
 public void CheckMailBox(string mailBox)
 {
     try
     {
         mailbox = clientImap.SelectMailbox(mailBox);
     }
     catch
     {
         clientImap.CreateMailbox(mailBox);
         mailbox = clientImap.SelectMailbox(mailBox);
     }
 }
コード例 #4
0
        public ActionResult Mailview(string MessageID, bool Received)
        {
            ImapClient imc = new ImapClient("imap.gmail.com", "*****@*****.**", "tsrhcbrixvjnbgza", AuthMethods.Login, 993, true);

            if (Received)
            {
                imc.SelectMailbox("INBOX");
            }
            else
            {
                imc.SelectMailbox("[Gmail]/Sent Mail");
            }

            return(View(imc.GetMessage(MessageID)));
        }
コード例 #5
0
        public List <GmailAPIService.CurrentMessage> GetAllMessages(string mail, string password)
        {
            List <GmailAPIService.CurrentMessage> messagesInfo = new List <GmailAPIService.CurrentMessage>();

            ImapClient ic = new ImapClient("imap.gmail.com", mail, password,
                                           AuthMethods.Login, 993, true);

            ic.SelectMailbox("INBOX");

            int messageCount = ic.GetMessageCount();

            MailMessage[] mm = ic.GetMessages(messageCount, messageCount - 30);
            foreach (MailMessage m in mm)
            {
                messagesInfo.Add(new GmailAPIService.CurrentMessage()
                {
                    Id      = m.MessageID.Replace('<', '"').Replace('>', '"'),
                    Date    = m.Date.ToString(),
                    From    = m.From.ToString(),
                    Subject = m.Subject
                });
            }
            ic.Dispose();
            return(messagesInfo);
        }
コード例 #6
0
ファイル: EmailMonitor.cs プロジェクト: sandeep526/NewUG12
        private static MailMessage[] GetEmails()
        {
            List <MailMessage> response = new List <MailMessage>();

            using (var imap = new ImapClient(Host, UserName, Password, ImapClient.AuthMethods.Login, Port, false))
            {
                imap.SelectMailbox("INBOX");

                // Get message count
                var messageCount = imap.GetMessageCount();

                if (messageCount == 0)
                {
                    return(response.ToArray());
                }

                var msgs = imap.GetMessages(0, (messageCount - 1)).ToArray();

                foreach (MailMessage msg in msgs)
                {
                    var flags = msg.Flags.ToString();
                    if (!flags.Contains("Deleted"))
                    {
                        response.Add(msg);
                    }
                }
            }

            return(response.ToArray());
        }
コード例 #7
0
        /// <summary>
        /// Function Name : ParseNewEmail
        /// Input Parameters : none
        /// Input Parameter Type : none
        /// Description:This method is going to record the event when an email is received to the Test email. It uses ImapClient which is available in AE.Net.Mail Nuget package.
        /// ImapClient has inbuilt properties to extract subject, body, sender information details from a newly received email
        /// </summary>
        /// <returns>
        /// Return Parameter : emailJson
        /// Return Parameter Type : string
        /// </returns>

        public string ParseNewEmail()
        {
            // Connect to the IMAP server. The 'true' parameter specifies to use SSL, which is important (for Gmail at least)
            ImapClient imapClient = new ImapClient(ConfigurationManager.AppSettings["ImapServer"], ConfigurationManager.AppSettings["UserId"], ConfigurationManager.AppSettings["Password"], AuthMethods.Login, 993, true);
            var        userName   = ConfigurationManager.AppSettings["UserID"];

            //  ImapClient imapClient = new ImapClient(ConfigurationManager.AppSettings["ImapServer"], "*****@*****.**", "7Ywy7N[S", AuthMethods.Login, 993, true);
            // Select a mailbox. Case-insensitive
            imapClient.SelectMailbox("INBOX");
            string emailJson = "";

            imapClient.NewMessage += (sender, e) =>
            {
                var           msg = imapClient.GetMessage(e.MessageCount - 1);
                UpdatePackage up  = new UpdatePackage();
                up.Updates     = ParseBody(msg.Body);
                up.Subject     = msg.Subject;
                up.Body        = msg.Body;
                up.ProjectName = ApplicationName;

                emailJson = JsonConvert.SerializeObject(up);
                string result = "";
                using (var client = new WebClient())
                {
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";
                    // result = client.UploadString("https://localhost:44300/ProjectUpdate/Update", "Post", emailJson);
                    result = client.UploadString("https://costcodevops.azurewebsites.net/ProjectUpdate/Update", "Post", emailJson);
                    Console.WriteLine(result);
                }
            };

            return(emailJson);
        }
コード例 #8
0
        public void DeleteAllMessages()
        {
            DashBoardMailBoxJob model = new DashBoardMailBoxJob();

            model.Inbox = new List <MailMessege>();
            string accountType = "gmail";

            try
            {
                EmailConfiguration email = new EmailConfiguration();
                switch (accountType)
                {
                case "Gmail":
                    // type your popserver
                    email.POPServer = "imap.gmail.com";
                    break;

                case "Outlook":
                    // type your popserver
                    email.POPServer = "outlook.office365.com";
                    break;
                }
                email.POPUsername  = UserName; // type your username credential
                email.POPpassword  = Password; // type your password credential
                email.IncomingPort = "993";
                email.IsPOPssl     = true;


                ImapClient ic = new ImapClient(email.POPServer, email.POPUsername, email.POPpassword, AuthMethods.Login, Convert.ToInt32(email.IncomingPort), (bool)email.IsPOPssl);
                // Select a mailbox. Case-insensitive
                ic.SelectMailbox("INBOX");
                int i        = 1;
                int msgcount = ic.GetMessageCount("INBOX");
                int end      = msgcount - 1;
                int start    = msgcount - msgcount;
                // Note that you must specify that headersonly = false
                // when using GetMesssages().
                MailMessage[] mm = ic.GetMessages(start, end, false);
                // var messages = ic.GetMessages(start, end, true);
                foreach (var it1 in mm)
                {
                    ic.DeleteMessage(it1);
                }


                ic.Dispose();
            }

            catch (Exception e)
            {
                model.mess = "Error occurred retrieving mail. " + e.Message;
            }
            finally
            {
            }
            //return model.Inbox;
        }
コード例 #9
0
        public static GAAutentication Autenticate(string _client_id, string _client_secret)
        {
            GAAutentication result = new GAAutentication();

            try
            {
                UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets {
                    ClientId = _client_id, ClientSecret = _client_secret
                },
                                                                                        new[] { "https://mail.google.com/ email" },
                                                                                        "Lindau",
                                                                                        CancellationToken.None,
                                                                                        new FileDataStore("Analytics.Auth.Store")).Result;
            }
            catch (Exception ex)
            {
                int i = 1;
            }

            if (result.credential != null)
            {
                result.service = new PlusService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = result.credential,
                    ApplicationName       = "Google mail",
                });


                Google.Apis.Plus.v1.Data.Person me = result.service.People.Get("me").Execute();

                Google.Apis.Plus.v1.Data.Person.EmailsData myAccountEmail = me.Emails.Where(a => a.Type == "account").FirstOrDefault();

                // 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", myAccountEmail.Value, result.credential.Token.AccessToken,
                                               ImapClient.AuthMethods.SaslOAuth, 993, true);
                // Select a mailbox. Case-insensitive
                ic.SelectMailbox("INBOX");
                Console.WriteLine(ic.GetMessageCount());
                // Get the first *11* messages. 0 is the first message;
                // and it also includes the 10th message, which is really the eleventh ;)
                // MailMessage represents, well, a message in your mailbox
                MailMessage[] mm = ic.GetMessages(0, 10);
                foreach (MailMessage m in mm)
                {
                    Console.WriteLine(m.Subject + " " + m.Date.ToString());
                }
                // Probably wiser to use a using statement
                ic.Dispose();
            }
            return(result);
        }
コード例 #10
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();
            }
        }
        public ActionResult GetMessegeBody(string id)
        {
            JsonResult result = new JsonResult();

            EmailConfiguration email = new EmailConfiguration();

            email.POPServer    = "imap.gmail.com";
            email.POPUsername  = "";
            email.POPpassword  = "";
            email.IncomingPort = "993";
            email.IsPOPssl     = true;

            ImapClient ic = new ImapClient(email.POPServer, email.POPUsername, email.POPpassword, AuthMethods.Login, Convert.ToInt32(email.IncomingPort), (bool)email.IsPOPssl);

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

            int         msgcount = ic.GetMessageCount("INBOX");
            MailMessage mm       = ic.GetMessage(id, false);

            if (mm.Attachments.Count() > 0)
            {
                foreach (var att in mm.Attachments)
                {
                    string fName;
                    fName = att.Filename;
                }
            }
            StringBuilder builder = new StringBuilder();

            builder.Append(mm.Body);
            string sm = builder.ToString();

            CustomerEmailDetails model = new CustomerEmailDetails();

            model.UID      = mm.Uid;
            model.subject  = mm.Subject;
            model.sender   = mm.From.ToString();
            model.sendDate = mm.Date;
            model.Body     = sm;
            if (mm.Attachments == null)
            {
            }
            else
            {
                model.Attachments = mm.Attachments;
            }

            return(View("CreateNewCustomer", model));
        }
コード例 #12
0
        private MailMessage GetLastMessageFromInBox(string folderName = "INBOX")
        {
            // Connect to the IMAP server.
            MailMessage message;

            WriteLine(EnvironmentSettings.TestAccountName);
            WriteLine(EnvironmentSettings.TestAccountPassword);
            using (var ic = new ImapClient(EnvironmentSettings.TestEmailServerHost, EnvironmentSettings.TestAccountName, EnvironmentSettings.TestAccountPassword, AuthMethods.Login, 993, true))
            {
                // Select folder and get the last mail.
                ic.SelectMailbox(folderName);
                message = ic.GetMessage(ic.GetMessageCount() - 1);
            }
            return(message);
        }
コード例 #13
0
        public static void Verify(string email, string pass, string ipmap = "imap.gmail.com", int port = 993)
        {
            string url = string.Empty;

            using (ImapClient ic = new ImapClient())
            {
                ic.Connect(ipmap, port, true, false);
                ic.Login(email, pass);
                ic.SelectMailbox("INBOX");
                int           mailcount = ic.GetMessageCount();
                MailMessage[] mails     = ic.GetMessages(mailcount - 5, mailcount - 1, false, false);

                foreach (var mm in mails.Reverse())
                {
                    bool flag = mm.Subject.Contains("Xác nhận") || mm.Subject.Contains("xác nhận");
                    if (flag)
                    {
                        string sbody       = mm.Body;
                        string regexString = "(?<=<a href=\").*?(?=\">)";
                        url = Regex.Match(sbody, regexString).ToString();
                        break;
                    }
                }

                ic.Dispose();
            }
            HttpRequest rq = new HttpRequest();

            rq.Cookies   = new CookieDictionary();
            rq.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36";

            if (url == string.Empty)
            {
                MessageBox.Show("Không tìm thấy email nào");
                return;
            }

            try
            {
                var result = rq.Get(url).ToString();
                WriteHtmlFile(result, "verify_mail.html");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
コード例 #14
0
        private void SetMessage(Message newMessage)
        {
            if (Message != null)
            {
                Message.PropertyChanged -= HandleModelPropertyChanged;
            }

            Message = newMessage;
            Message.PropertyChanged += HandleModelPropertyChanged;

            Date = ImapParser.ParseDate(Message.DateString);

            if (string.IsNullOrEmpty(Message.Body))
            {
                DownloadMessageBodyAsync();
            }
            else
            {
                // Loading a message whose body has already been downloaded.
                TextBody          = MimeUtility.GetTextBody(Message.Body);
                HtmlBody          = MimeUtility.GetHtmlBody(Message.Body);
                ProcessedHtmlBody = ProcessHtmlBody(HtmlBody);
                LoadAttachments(Message.Body);

                if (!Message.IsSeen)
                {
                    // Set the \Seen flag.
                    Message.IsSeen = true;
                    DatabaseManager.Update(Message);

                    Task.Run(() => {
                        ImapClient imap = new ImapClient(notification.SelectedAccount);
                        if (imap.Connect())
                        {
                            // Not readonly because we need to set the \Seen flag.
                            bool readOnly = false;
                            if (imap.SelectMailbox(notification.SelectedMailbox.DirectoryPath, readOnly))
                            {
                                imap.SetFlag(ImapClient.FlagAction.Add, Message.Uid, "\\Seen");
                            }

                            imap.Disconnect();
                        }
                    });
                }
            }
        }
コード例 #15
0
        public ActionResult ReceiveEmail(int id)
        {
            //We find user which is logged now
            var user      = UserManager.FindById(User.Identity.GetUserId());
            var userEmail = user.Email;
            var userName  = User.Identity.GetUserName();

            //We read password of our user from cookie - this cookie is created when the user is logged to application
            string PasswordCookie = Request.Cookies["PasswordCookie"].Value;
            // Connect to the IMAP server. The 'true' parameter specifies to use SSL
            // which is important (for Gmail at least)
            ImapClient ic = new ImapClient("127.0.0.1", userEmail, PasswordCookie, AuthMethods.Login, 143
                                           , false);

            // Select a mailbox. Case-insensitive
            ic.SelectMailbox("INBOX");
            // Get the first *11* messages. 0 is the first message;
            // and it also includes the 10th message, which is really the eleventh ;)
            // MailMessage represents, well, a message in your mailbox
            //This is list which has all messages from inbox from email server for logged user
            List <EmailVM> ListOfMessages = new List <EmailVM>();

            MailMessage[] mm = ic.GetMessages(0, 50, false);
            //We rewrite messages from IMAPX lib model class to our model class which is used in our view.
            foreach (MailMessage m in mm)
            {
                var ccUsers = m.Cc.ToArray(); //CCusers is array in our view so we have to convert ccusers from impax to this array
                EDictionaryUser[] EmailCCUsers = new EDictionaryUser[m.Cc.Count];
                for (int EmailCCUserNumber = 0; EmailCCUserNumber < m.Cc.Count; EmailCCUserNumber++)
                {
                    EmailCCUsers[EmailCCUserNumber] = new EDictionaryUser()
                    {
                        Email = ccUsers[EmailCCUserNumber].Address
                    };
                }
                ;
                ListOfMessages.Add(new EmailVM()
                {
                    CClist = EmailCCUsers, To = m.To.ToString(), From = m.From.Address, Body = m.Body.ToString(), Subject = m.Subject.ToString(), Date = m.Date
                });
            }
            //We diconnected with email server
            ic.Dispose();
            //Redirect to receive email view
            return(View("ReceiveEmail", ListOfMessages));
        }
コード例 #16
0
        private static string GetEmail(string v1, string v2)
        {
            ImapClient client = new ImapClient("imap.openmailbox.org", v1, v2, AuthMethods.Login, 993, true);

            client.SelectMailbox("INBOX");

            MailMessage[] listemail = client.GetMessages(0, 20);
            MailMessage   email     = listemail[12];

            if (String.IsNullOrEmpty(email.Body))
            {
                string body = client.GetMessage(email.Uid).Subject;
                client.Dispose();
                return(body);
            }
            client.Dispose();
            return(email.Subject);
        }
コード例 #17
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);
        }
コード例 #18
0
 // This is where all the magic happens.
 void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
     StatusBarText = "Connecting to server...";
     try
     {
         ImapClient ic = new ImapClient(ServerName, Username, Password, AuthMethods.Login, 993, true);
         ic.SelectMailbox("INBOX");
         Lazy <MailMessage>[] messages = ic.SearchMessages(SearchCondition.Unseen(), true, false);
         display.printNumber(messages.Length);
         StatusBarText = "Number of unread messages: " + messages.Length;
         ic.Disconnect();
         ic.Dispose();
     }
     catch (Exception ex)
     {
         StatusBarText = ex.Message;
         StopRunning();
     }
 }
コード例 #19
0
        ///////////////////////////////////////////////////

        private bool Connect()
        {
            if (imap_client != null)
            {
                imap_client.Disconnect();
            }
            imap_client = null;
            bool success = false;

            try {
                imap_client            = new ImapClient();
                imap_client.AuthMethod = AUTH_METHOD;
                imap_client.Port       = PORT;
                imap_client.Ssl        = USE_SSL;
                imap_client.Connect(GMAIL_SERVER);

                success = imap_client.Login(username, password);

                if (!success)
                {
                    Log.Error("IMAP connection unsuccessful: {0}", imap_client.LastError);
                }
                else
                {
                    Mailbox search_mailbox = imap_client.SelectMailbox(search_folder);
                    success = (search_mailbox != null);
                    if (!success)
                    {
                        Log.Error("Selection folder unsuccessful: {0}", imap_client.LastError);
                    }
                }
            } catch (Exception e) {
                Log.Error(e, "GMailSearchDriver: Error in connecting to {0} with username {1}", GMAIL_SERVER, username);
            }

            if (!success && imap_client != null)
            {
                imap_client.Disconnect();
            }

            return(success);
        }
コード例 #20
0
        public void Start()
        {
            TraceLog.TraceInfo("MailWorker started");
            string hostname = System.Configuration.ConfigurationManager.AppSettings["Hostname"];
            int port = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Port"]);
            string username = System.Configuration.ConfigurationManager.AppSettings["Username"];
            string password = System.Configuration.ConfigurationManager.AppSettings["Password"];

#if IDLE
            // idle support means we can use an event-based programming model to get informed when 
            var mre = new System.Threading.ManualResetEvent(false);
            using (var imap = new ImapClient(hostname, username, password, ImapClient.AuthMethods.Login, port, true))
                TraceLine("Connected", "Information");
                imap.SelectMailbox("inbox");

                // a new message comes in
                imap.NewMessage += Imap_NewMessage;
                while (!mre.WaitOne(5000)) //low for the sake of testing; typical timeout is 30 minutes
                    imap.Noop();
            }
コード例 #21
0
ファイル: Account.cs プロジェクト: seavnc/MailChecker
        private List <MailMessage> Fetch_UnseenMails(ImapClient client)
        {
            try
            {
                List <MailMessage> myMsg = new List <MailMessage>();

                client.SelectMailbox("INBOX");
                System.Lazy <MailMessage>[] myMessages = client.SearchMessages(aenetmail_csharp.Imap.SearchCondition.Unseen());
                foreach (System.Lazy <MailMessage> message in myMessages)
                {
                    myMsg.Add(message.Value);
                }
                return(myMsg);
            }
            catch
            {
                List <MailMessage> myMessages = new List <MailMessage>();
                return(myMessages);
            }
        }
コード例 #22
0
        public IEnumerable <MailMessage> SearchEmail(string mailBox, string searchString)
        {
            ConnectToServer();
            List <MailMessage> result = new List <MailMessage>();

            try
            {
                Imap.SelectMailbox(mailBox);
            }
            catch
            {
                throw new MailException("Something went wrong while selecting the mailbox '" + mailBox + "' possibly it does not exist");
            }
            Lazy <MailMessage>[] LazyMailArray = Imap.SearchMessages(SearchCondition.Subject(searchString));
            foreach (Lazy <MailMessage> LM in LazyMailArray)
            {
                result.Add(LM.Value);
            }
            DisconnectFromServer();
            return(result);
        }
コード例 #23
0
        private async void DownloadMessageBodyAsync()
        {
            Loading = true;

            string msgBody = string.Empty;

            await Task.Run(() => {
                ImapClient imap = new ImapClient(notification.SelectedAccount);
                if (imap.Connect())
                {
                    // Not readonly because we need to set the \Seen flag.
                    bool readOnly = false;
                    if (imap.SelectMailbox(notification.SelectedMailbox.DirectoryPath, readOnly))
                    {
                        msgBody = imap.FetchBody(Message.Uid);
                    }

                    imap.Disconnect();

                    if (!Message.IsSeen)
                    {
                        Message.IsSeen = true;

                        // The server should automatically set the \Seen flag when BODY is fetched.
                        // We shouldn't have to send command for this.
                    }
                }
            });

            if (msgBody != string.Empty)
            {
                Message.Body = msgBody;
            }

            // Store the Body and IsSeen flag to the database.
            DatabaseManager.Update(Message);

            Loading = false;
        }
コード例 #24
0
        private void PasswordEmailButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ic = new ImapClient("imap.gmail.com", "*****@*****.**", PasswordrEmailPB.Password,
                                    AuthMethods.Login, 993, true);


                ic.SelectMailbox("INBOX");


                MailMessage[]      mm = ic.GetMessages(0, ic.GetMessageCount(), true, false);
                List <MailMessage> mms;
                mms = mm.Reverse().ToList();
                mms.RemoveAll(r => r.Encoding != Encoding.UTF8);
                EmailListView.ItemsSource = mms;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
コード例 #25
0
        public string GetMailText(DateTime dt)
        {
            try
            {
                var res = ic.SelectMailbox("INBOX");
            }
            catch
            {
                return("123456");
            }
            MailMessage[] mm = ic.GetMessages(ic.GetMessageCount() - 1, ic.GetMessageCount());

            if (mm[mm.Length - 1].Date > dt)
            {
                MailMessage message = ic.GetMessage(mm[mm.Length - 1].Uid);

                string     path       = $"message{r}.html";
                FileStream filestream = new FileStream(path, FileMode.Create);
                filestream.Close();
                StreamWriter file = new StreamWriter(path);
                file.Write(message.Body);
                file.Close();

                Thread.Sleep(5000);
                HtmlAgilityPack.HtmlWeb web = new HtmlWeb();

                HtmlAgilityPack.HtmlDocument doc = web.Load(Environment.CurrentDirectory + @"\" + path);

                var    nodes  = doc.DocumentNode.SelectNodes("//p/font");
                string result = nodes[0].InnerText;

                return(result);//message.Body.ToString();
            }
            else
            {
                Thread.Sleep(5000);
                return(GetMailText(dt));
            }
        }
コード例 #26
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);
        }
コード例 #27
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);
                }
            }
        }
コード例 #28
0
ファイル: Account.cs プロジェクト: meehi/MailChecker
        private List<MailMessage> Fetch_UnseenMails(ImapClient client)
        {
            try
            {
                List<MailMessage> myMsg = new List<MailMessage>();

                client.SelectMailbox("INBOX");
                System.Lazy<MailMessage>[] myMessages = client.SearchMessages(aenetmail_csharp.Imap.SearchCondition.Unseen());
                foreach (System.Lazy<MailMessage> message in myMessages)
                    myMsg.Add(message.Value);
                return myMsg;
            }
            catch
            {
                List<MailMessage> myMessages = new List<MailMessage>();
                return myMessages;
            }
        }
コード例 #29
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();
            }
        }
        private DashBoardMailBoxJob ReceiveMails()
        {
            DashBoardMailBoxJob model = new DashBoardMailBoxJob();

            model.Inbox = new List <MailMessege>();

            try
            {
                EmailConfiguration email = new EmailConfiguration();
                email.POPServer    = "imap.gmail.com"; // type your popserver
                email.POPUsername  = "";               // type your username credential
                email.POPpassword  = "";               // type your password credential
                email.IncomingPort = "993";
                email.IsPOPssl     = true;


                int        success = 0;
                int        fail    = 0;
                ImapClient ic      = new ImapClient(email.POPServer, email.POPUsername, email.POPpassword, AuthMethods.Login, Convert.ToInt32(email.IncomingPort), (bool)email.IsPOPssl);
                // Select a mailbox. Case-insensitive
                ic.SelectMailbox("INBOX");
                int i        = 1;
                int msgcount = ic.GetMessageCount("INBOX");
                int end      = msgcount - 1;
                int start    = msgcount - 40;
                // Note that you must specify that headersonly = false
                // when using GetMesssages().
                MailMessage[] mm = ic.GetMessages(start, end, false);
                foreach (var item in mm)
                {
                    MailMessege obj = new MailMessege();
                    try
                    {
                        obj.UID      = item.Uid;
                        obj.subject  = item.Subject;
                        obj.sender   = item.From.ToString();
                        obj.sendDate = item.Date;
                        if (item.Attachments == null)
                        {
                        }
                        else
                        {
                            obj.Attachments = item.Attachments;
                        }

                        model.Inbox.Add(obj);
                        success++;
                    }
                    catch (Exception e)
                    {
                        DefaultLogger.Log.LogError(
                            "TestForm: Message fetching failed: " + e.Message + "\r\n" +
                            "Stack trace:\r\n" +
                            e.StackTrace);
                        fail++;
                    }
                    i++;
                }
                ic.Dispose();
                model.Inbox = model.Inbox.OrderByDescending(m => m.sendDate).ToList();
                model.mess  = "Mail received!\nSuccesses: " + success + "\nFailed: " + fail + "\nMessage fetching done";

                if (fail > 0)
                {
                    model.mess = "Since some of the emails were not parsed correctly (exceptions were thrown)\r\n" +
                                 "please consider sending your log file to the developer for fixing.\r\n" +
                                 "If you are able to include any extra information, please do so.";
                }
            }

            catch (Exception e)
            {
                model.mess = "Error occurred retrieving mail. " + e.Message;
            }
            finally
            {
            }
            return(model);
        }
コード例 #31
0
        public List <Expenses> GetMails(string _client_id, string _client_secret)
        {
            CustomMailService result      = new CustomMailService();
            List <Expenses>   emailModels = new List <Expenses>();
            //If you want to test new gmail account,
            //Go to the browser, log off, log in with the new account,
            //and then change this 'tmpUser'
            var tmpUser = "******";

            try
            {
                result.credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets {
                    ClientId = _client_id, ClientSecret = _client_secret
                },
                                                                                new[] { "https://mail.google.com/ email" },
                                                                                tmpUser,
                                                                                CancellationToken.None,
                                                                                new FileDataStore("Analytics.Auth.Store")).Result;
            }
            catch (Exception ex)
            {
            }

            if (result.credential != null)
            {
                result.service = new PlusService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = result.credential,
                    ApplicationName       = "Google mail",
                });


                Google.Apis.Plus.v1.Data.Person me = result.service.People.Get("me").Execute();

                Google.Apis.Plus.v1.Data.Person.EmailsData myAccountEmail = me.Emails.Where(a => a.Type == "account").FirstOrDefault();

                // Connect to the IMAP server. The 'true' parameter specifies to use SSL
                // which is important (for Gmail at least)
                ImapClient imapClient = new ImapClient("imap.gmail.com", myAccountEmail.Value, result.credential.Token.AccessToken,
                                                       ImapClient.AuthMethods.SaslOAuth, 993, true);

                var mailBox = imapClient.SelectMailbox("FNB");

                Console.WriteLine("ListMailboxes");

                Console.WriteLine(mailBox.Name);
                var original = Console.ForegroundColor;

                var examine = imapClient.Examine(mailBox.Name);
                if (examine != null)
                {
                    Console.WriteLine(" - Count: " + imapClient.GetMessageCount());

                    //Get One Email per folder

                    MailMessage[] mm = imapClient.GetMessages(0, imapClient.GetMessageCount());
                    Console.ForegroundColor = ConsoleColor.Blue;
                    var counter = 0;
                    foreach (MailMessage m in mm)
                    {
                        if (m.Date > DateTime.Now.AddDays(-30))
                        {
                            if (m.Subject.Contains("reserved for purchase") || m.Subject.Contains("paid from cheq"))
                            {
                                var substring = m.Subject.Substring(7, 10);
                                var number    = Regex.Split(substring, @"[^0-9\.]+")[1];
                                var amount    = Convert.ToDouble(number, CultureInfo.InvariantCulture);
                                var email     = new Expenses()
                                {
                                    PaymentType = PaymentType.Bill, Name = m.Subject, Amount = amount, Id = m.MessageID, PaymentDate = m.Date
                                };
                                if (m.Subject.Contains("paid from cheq"))
                                {
                                    email.PaymentType = PaymentType.Buy;
                                }
                                emailModels.Add(email);
                                counter++;
                            }
                        }
                    }
                }
                else
                {
                }

                imapClient.Dispose();
            }
            return(emailModels);
        }