예제 #1
0
        public List <Email> GetArchiveEmails()
        {
            int errorLevel = 0;

            Log.Append(String.Format("Getting new emails from archive..."));


            List <Email> newEmails = new List <Email>();

            int emailSyncCount = 0;

            using (var client = new MailKit.Net.Imap.ImapClient())
            {
                try
                {
                    //For demo-purposes, accept all SSL certificates
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    #region Connect using receiving parameters

                    try
                    {
                        client.Connect(ReceivingProtocol, Convert.ToInt32(ReceivingPort), true);
                    }
                    catch
                    {
                        Log.Append(String.Format("ERROR: Failed to connect to {0} using {1}:{2}", Email,
                                                 ReceivingProtocol, ReceivingPort));
                        return(new List <Email>());
                    }

                    #endregion

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    #region Login using credentials

                    try
                    {
                        client.Authenticate(Email, Password);
                    }
                    catch
                    {
                        Log.Append(String.Format("ERROR: Failed to login using user credentials for '{0}'", Email));
                        return(new List <Email>());
                    }

                    #endregion

                    #region Inbox

                    // The Inbox folder is always available on all IMAP servers...
                    var inbox = client.Inbox;
                    inbox.Open(FolderAccess.ReadWrite);

                    var query = SearchQuery.DeliveredAfter(LastUpdateTime);

                    foreach (var uid in inbox.Search(query))
                    {
                        try
                        {
                            if (Readiness.CheckTerminationStatus(true))
                            {
                                break;
                            }

                            string workingID = Global.GetAttachmentID();

                            try
                            {
                                MimeMessage message = inbox.GetMessage(uid);

                                var date = message.Date.ToString();

                                Email email = new Email()
                                {
                                    UID      = uid.ToString(),
                                    ID       = workingID,
                                    MailDate = Convert.ToDateTime(date),
                                    From     = message.From.ToString(),
                                    To       = Email,
                                    Subject  = message.Subject,
                                };

                                if (email.Subject.Trim().Length != 6 || !email.Subject.Trim().All(char.IsDigit))
                                {
                                    Random r = new Random();
                                    email.CreateEmailMsgFile(message,
                                                             ArchivesChecker._errorPath + DateTime.Now.Month + "_" + DateTime.Now.Day +
                                                             "_" + DateTime.Now.Year + "_" + r.Next(10000, 99999), true);
                                }
                                else
                                {
                                    emailSyncCount++;

                                    email.CreateEmailMsgFile(message, ArchivesChecker.CreateArchiveDirectory(email.Subject) + @"\" + email.Subject);

                                    newEmails.Add(email);
                                }

                                inbox.AddFlags(new[] { uid }, MessageFlags.Deleted, true);
                                inbox.Expunge();
                            }
                            catch
                            {
                                Log.Append(String.Format("ERROR: Email can't be processed with ID={0}", workingID));
                            }
                        }
                        catch (Exception ex)
                        {
                            errorLevel++;
                            Log.Append(String.Format("ERROR [Inbox]: {0}", ex));
                            // Undetermined error from automated system
                        }
                    }

                    #endregion

                    #region Subfolders

                    var personal = client.GetFolder(client.PersonalNamespaces[0]);
                    foreach (var folder in personal.GetSubfolders(false))
                    {
                        if (folder.Name.ToLower() != "sent")
                        {
                            if (Readiness.CheckTerminationStatus(true))
                            {
                                break;
                            }

                            try
                            {
                                folder.Open(FolderAccess.ReadOnly);

                                query = SearchQuery.DeliveredAfter(LastUpdateTime);

                                foreach (var uid in folder.Search(query))
                                {
                                    if (Readiness.CheckTerminationStatus())
                                    {
                                        return(newEmails);
                                    }

                                    MimeMessage message = folder.GetMessage(uid);

                                    var date = message.Date.ToString();

                                    Email email = new Email
                                    {
                                        UID      = uid.ToString(),
                                        ID       = Global.GetAttachmentID(),
                                        MailDate = Convert.ToDateTime(date),
                                        From     = message.From.ToString(),
                                        To       = Email,
                                        Subject  = message.Subject,
                                    };

                                    if (email.Subject.Trim().Length != 6 || !email.Subject.Trim().All(char.IsDigit))
                                    {
                                        Random r = new Random();
                                        email.CreateEmailMsgFile(message,
                                                                 ArchivesChecker._errorPath + DateTime.Now.Month + "_" + DateTime.Now.Day +
                                                                 "_" + DateTime.Now.Year + "_" + r.Next(10000, 99999));
                                    }
                                    else
                                    {
                                        emailSyncCount++;

                                        email.CreateEmailMsgFile(message, ArchivesChecker.CreateArchiveDirectory(email.Subject) + @"\" + email.Subject);

                                        newEmails.Add(email);
                                    }


                                    inbox.AddFlags(new[] { uid }, MessageFlags.Deleted, true);
                                    inbox.Expunge();
                                }
                            }
                            catch
                            {
                                Log.Append(String.Format("  Sub folder IMAP retrieval error for folder=\"{0}\"",
                                                         folder.Name));
                            }
                        }
                    }

                    #endregion

                    client.Disconnect(true);
                }
                catch (Exception ex)
                {
                    errorLevel++;
                    Log.Append(String.Format("ERROR [Overall]: {0}", ex));
                }
            }


            Log.Append(String.Format("{0} emails archived.", emailSyncCount));

            if (errorLevel <= 0)
            {
                Log.Append("Complete!");
            }

            return(newEmails);
        }
예제 #2
0
        public List <Email> GetEmails()
        {
            if (Global.isSyncing)
            {
                Log.Append("Error: Existing sync in progress");
                return(new List <Email>());
            }

            Global.isSyncing = true;

            int errorLevel = 0;

            Log.Append(String.Format("Getting new emails (since {1}) from '{0}'...", Email, LastUpdateTime.ToShortDateString()));

            // Generate the list of uids from current emails stored for current user (used to check if email already exists)
            List <string> ExistingUID = Global.EmailList.Where(x => x.To == Email && x.MailDate >= LastUpdateTime.AddDays(-5)).Select(y => y.UID).ToList();

            List <Email> newEmails = new List <Email>();

            int emailSyncCount = 0;

            using (var client = new MailKit.Net.Imap.ImapClient())
            {
                try
                {
                    //For demo-purposes, accept all SSL certificates
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    #region Connect using receiving parameters

                    try
                    {
                        client.Connect(ReceivingProtocol, Convert.ToInt32(ReceivingPort), true);
                    }
                    catch
                    {
                        Log.Append(String.Format("ERROR: Failed to connect to {0} using {1}:{2}", Email,
                                                 ReceivingProtocol, ReceivingPort));
                        return(new List <Email>());
                    }

                    #endregion

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    #region Login using credentials

                    try
                    {
                        client.Authenticate(Email, Password);
                    }
                    catch
                    {
                        Log.Append(String.Format("ERROR: Failed to login using user credentials for '{0}'", Email));
                        return(new List <Email>());
                    }

                    #endregion

                    #region Inbox

                    // The Inbox folder is always available on all IMAP servers...
                    var inbox = client.Inbox;
                    inbox.Open(FolderAccess.ReadOnly);

                    Log.Append("  Checking 'Inbox'");

                    var query = SearchQuery.DeliveredAfter(LastUpdateTime);

                    foreach (var uid in inbox.Search(query))
                    {
                        try
                        {
                            if (Readiness.CheckTerminationStatus(true))
                            {
                                break;
                            }

                            string workingID = Global.GetAttachmentID();

                            try
                            {
                                // Verify that this email does not exist.
                                if (!ExistingUID.Contains(uid.ToString()))
                                {
                                    MimeMessage message = inbox.GetMessage(uid);

                                    var date = message.Date.ToString();

                                    Email email = new Email()
                                    {
                                        UID      = uid.ToString(),
                                        ID       = workingID,
                                        MailDate = Convert.ToDateTime(date),
                                        From     = message.From.ToString(),
                                        To       = Email,
                                        Subject  = message.Subject,
                                    };

                                    emailSyncCount++;

                                    email.CreateEmailMsgFile(message);
                                    email.RetrieveMsg();
                                    Global.AppendEmail(email);
                                    newEmails.Add(email);
                                }
                            }
                            catch
                            {
                                Log.Append(String.Format("ERROR: Email can't be processed with ID={0}", workingID));
                            }
                        }
                        catch (Exception ex)
                        {
                            errorLevel++;
                            Log.Append(String.Format("ERROR [Inbox]: {0}", ex));
                            // Undetermined error from automated system
                        }
                    }

                    #endregion

                    #region Subfolders

                    var personal = client.GetFolder(client.PersonalNamespaces[0]);
                    foreach (var folder in personal.GetSubfolders(false))
                    {
                        Log.Append(String.Format("  Checking folder '{0}'", folder.Name));

                        if (folder.Name.ToLower() != "sent")
                        {
                            if (Readiness.CheckTerminationStatus(true))
                            {
                                break;
                            }

                            try
                            {
                                folder.Open(FolderAccess.ReadOnly);

                                query = SearchQuery.DeliveredAfter(LastUpdateTime);

                                foreach (var uid in folder.Search(query))
                                {
                                    if (Readiness.CheckTerminationStatus())
                                    {
                                        return(newEmails);
                                    }

                                    // Verify that this email does not exist.
                                    if (!ExistingUID.Contains(uid.ToString()))
                                    {
                                        MimeMessage message = folder.GetMessage(uid);

                                        var date = message.Date.ToString();

                                        Email email = new Email()
                                        {
                                            UID      = uid.ToString(),
                                            ID       = Global.GetAttachmentID(),
                                            MailDate = Convert.ToDateTime(date),
                                            From     = message.From.ToString(),
                                            To       = Email,
                                            Subject  = message.Subject,
                                        };

                                        emailSyncCount++;

                                        email.CreateEmailMsgFile(message);
                                        email.RetrieveMsg();
                                        Global.AppendEmail(email);
                                        newEmails.Add(email);
                                    }
                                }
                            }
                            catch
                            {
                                Log.Append(String.Format("  Sub folder IMAP retrieval error for folder=\"{0}\"",
                                                         folder.Name));
                            }
                        }
                    }

                    #endregion

                    client.Disconnect(true);
                }
                catch (Exception ex)
                {
                    errorLevel++;
                    Log.Append(String.Format("ERROR [Overall]: {0}", ex));
                }
            }


            Log.Append(String.Format("{0} emails synced.", emailSyncCount));

            if (errorLevel <= 0)
            {
                LastUpdateTime = DateTime.Now;
                Log.Append("Complete!");
            }

            GetEmailCount();
            Global.SaveSettings();
            Global.ExportEmailFile();

            Global.isSyncing = false;

            // Sort by date
            Global.EmailList = Global.EmailList.OrderByDescending(x => x.MailDate).ToList();

            return(newEmails);
        }