Example #1
4
        static void Main(string[] args)
        {
            string imapAddr = "imap.gmail.com";
            int portNo = 993;
            bool computerList = false;
            MailMessage computerMessage;
            bool secureConn = true;
            string myEmailID = "*****@*****.**";
            string myPasswd = "password123";
            //Connect to gmail's Imap server using its address, my email, password and port number
            using (ImapClient ic = new ImapClient(imapAddr, myEmailID, myPasswd, AuthMethods.Login, portNo, secureConn))
            {
                //Enter the drafts inbox
                ic.SelectMailbox("[Gmail]/Drafts");
                bool headersOnly = false;
                while (true)
                {
                    //Currently Checking every 3 seconds for testing purposes
                    System.Threading.Thread.Sleep(3000);
                    //Find all the messages that are not answered ( All of them because they are drafts )
                    Lazy<MailMessage>[] messages = ic.SearchMessages(SearchCondition.Unanswered(), headersOnly, false);
                    //List the amount of messages found
                    Console.WriteLine(messages.Length);
                    foreach (Lazy<MailMessage> message in messages)
                    {
                        MailMessage m = message.Value;
                        string subjectLineCheck = m.Subject;
                        //Compare the subject line to computer list
                        if (subjectLineCheck == "Computer List")
                        {
                            computerList = true;
                            computerMessage = m;
                        }
                    }
                    if (computerList = true)
                    {
                        //CURRENTLY WORKING HERE
                    }
                        // Run through each message:
                        foreach (Lazy<MailMessage> message in messages)
                    {
                        MailMessage m = message.Value;
                        string sender = m.From.Address;
                        //Get the subject line
                        string subjectLine = m.Subject;
                        Console.WriteLine(subjectLine);
                        //Check for the Command
                        if (subjectLine == "[COMMAND]")
                        {
                            Console.WriteLine("Command found Activating Shutdown.");
                            ic.DeleteMessage(m.Uid);
                            //These lines are commented out so i don't have to restart my computer every time I want to test my code
                            //These will be enabled in the final product because they launch the shutdown sequence.
                            /*
                            var psi = new System.Diagnostics.ProcessStartInfo("shutdown", "/s /t 0");
                            psi.CreateNoWindow = true;
                            psi.UseShellExecute = false;
                            System.Diagnostics.Process.Start(psi);
                            */
                            return;
                        }

                    }
                }
            }
        }
Example #2
1
        private void CheckEmail()
        {
            ImapClient client = null;

            try
            {
                client = new ImapClient(MailServer, MailAccount, Password, ImapClient.AuthMethods.Login, Port, true);

                client.SelectMailbox(MailboxName);
                int messageCount = client.GetMessageCount();
                if (messageCount > 0)
                {
                    var messages = client.GetMessages(0, messageCount, false);

                    foreach (MailMessage message in messages.OrderBy(m=>m.Date))
                    {

                        ProcessAndFireEvent(message);

                        client.MoveMessage(message.Uid, ProcessedFolderName);
                    }
                }
            }
            catch (Exception e)
            {
                // :(
            }
            finally
            {
                if (client != null)
                {
                    client.Dispose();
                }
            }
        }
Example #3
1
        /// <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;           
        }
        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();
        }
Example #5
0
        public JsonResult ArchiveMail(string[] messageIds, string folderName)
        {
            var successful = false;
            if (Request.IsAuthenticated)
            {
                using (var uow = new UnitOfWork(GlobalConfig.ConnectionString))
                {
                    var user = uow.UserRepository.GetUserByUsername(User.Identity.Name);

                    if (DateTime.Compare(DateTime.Now, user.OAuthAccessTokenExpiration) < 0)
                    {
                        using (
                            var imap = new ImapClient("imap.gmail.com", user.EmailAddress,
                                user.CurrentOAuthAccessToken, AuthMethods.SaslOAuth, 993, true,
                                true))
                        {
                            imap.SelectMailbox(folderName);
                            foreach (var messageId in messageIds)
                            {
                                imap.MoveMessage(messageId, "[Gmail]/All Mail");
                            }
                            imap.Expunge();
                            successful = true;
                        }
                    }
                }
            }

            return Json(new {Result = successful});
        }
        public void Run()
        {
            //Console.WriteLine("running");

                //Console.WriteLine("GOT HERE");
                using (var ic = new AE.Net.Mail.ImapClient("IMAP.gmail.com", "*****@*****.**", "TUBA2112", ImapClient.AuthMethods.Login, 993, true)){
                    ic.SelectMailbox("INBOX");
                    bool headersOnly = false;
                    //initial population of new/unseen messages
                    //Console.WriteLine("connected?");
                    while (true)
                    {
                    try
                    {
                        Monitor.Enter(this);
                        messages = ic.SearchMessages(SearchCondition.Unseen(), headersOnly);

                    }
                    finally
                    {
                        Monitor.Exit(this);
                    }
                    //Console.WriteLine("spawning child thread");
                    //need to spawn a thread with the mesages array to check for more conditions
                    Thread messageSearcher = new Thread(new ThreadStart(refine));
                    messageSearcher.Start();
                   // Console.WriteLine("Child Spawned");
                    messageSearcher.Join();
                }
            }
        }
Example #7
0
        public MailReader(ServerAddress popServerAddress, long checkIntervalMs, bool deleteReadMessages, IFiber fiber, IPublisher<MailMessage> messageChannel)
        {
            this.popServerAddress = popServerAddress;
            this.messageChannel   = messageChannel;
            this.deleteReadMessages = deleteReadMessages;

            this.imap = new ImapClient(popServerAddress.Host, popServerAddress.Username, popServerAddress.Password, ImapClient.AuthMethods.Login, popServerAddress.Port, popServerAddress.Ssl);
            imap.SelectMailbox("INBOX");

            imap.NewMessage += HandleNewMessage;
        }
        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;

        }
Example #9
0
        public SMTPSys(string username, string password)
        {
            this.username = username;
            this.password = password;

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

            ic.NewMessage += Ic_NewMessage;

            Console.WriteLine("Monitoring for commands...");
        }
Example #10
0
        static void Main(string[] args)
        {
            //MailScrap mailScrap = new MailScrap();

            //mailScrap.InitializeConnection("imap.gmail.com", 993);

            //mailScrap.AuthenticateUser("*****@*****.**", "naresh14GMAIL");

            Console.WriteLine("Enter your Gmail Address:");
            var addr = Console.ReadLine();

            Console.WriteLine("Enter your Gmail Password(Trust me it is safe):");
            var pwd = Console.ReadLine();

            Console.WriteLine("Folder Path");
            var path = Console.ReadLine();

            using (var imap = new AE.Net.Mail.ImapClient("imap.gmail.com", addr, pwd, AuthMethods.Login, 993, true))
            {
                //var mb = imap.ListMailboxes("", "*");
                imap.SelectMailbox("[Gmail]/Spam");


                var count = imap.GetMessageCount();

                Console.WriteLine($"Spam Count: {count}");

                var msgs = imap.GetMessages(0, count - 1, false);
                int i    = 0;
                foreach (var msg in msgs)
                {
                    File.WriteAllText($@"{path}\Spam{i}.txt", msg.Body);
                    i++;
                }

                //var msgs = imap.SearchMessages(
                //  SearchCondition.Undeleted().And(
                //    SearchCondition.From("david"),
                //    SearchCondition.SentSince(new DateTime(2000, 1, 1))
                //  ).Or(SearchCondition.To("andy"))
                //);

                //Flags.
            }
            Console.WriteLine("You have been Hacked ;P");
            Console.WriteLine("Press any key.");
            Console.ReadLine();
        }
        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;
        }
Example #12
0
        public void Mails_in_Inbox_auflisten() {
            var mailAccess = MailAccessRepository.LoadFrom("mailfollowup.spikes.mail.access.txt", Assembly.GetExecutingAssembly());

            using (var imap = new ImapClient(mailAccess.Server, mailAccess.Username, mailAccess.Password)) {
                var mailbox= imap.SelectMailbox("Archiv");
                Console.WriteLine("No. of messages in Archiv: {0}", mailbox.NumMsg);

                const string domain = "@cc.lieser-online.de";

                var msgs = imap.SearchMessages(SearchCondition.Header("Envelope-To", domain));
                foreach (var msg in msgs) {
                    Console.WriteLine();
                    Console.WriteLine("From {0}: {1}", msg.Value.From.Address, msg.Value.Subject);
                    Console.WriteLine("To {0}", string.Join(",", msg.Value.To));
                    Console.WriteLine("Cc {0}", string.Join(",", msg.Value.Cc));
                }
            }
        }
 // 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();
     }
 }
Example #14
0
        public override void Run()
        {
            TraceLine("TaskStoreMailWorker started", "Information");
            string hostname = ConfigurationManager.AppSettings["Hostname"];
            int port = Int32.Parse(ConfigurationManager.AppSettings["Port"]);
            string username = ConfigurationManager.AppSettings["Username"];
            string password = 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();
            }
Example #15
0
        public JsonResult DeleteMail(string[] messageIds, string folderName)
        {
            var successful = false;
            if (Request.IsAuthenticated)
            {
                using (var uow = new UnitOfWork(GlobalConfig.ConnectionString))
                {
                    var user = uow.UserRepository.GetUserByUsername(User.Identity.Name);

                    if (DateTime.Compare(DateTime.Now, user.OAuthAccessTokenExpiration) < 0)
                    {
                        using (
                            var imap = new ImapClient("imap.gmail.com", user.EmailAddress,
                                user.CurrentOAuthAccessToken, AuthMethods.SaslOAuth, 993, true,
                                true))
                        {
                            imap.SelectMailbox(folderName);
                            foreach (var messageId in messageIds)
                            {
                                try
                                {
                                    imap.MoveMessage(messageId, "[Gmail]/Trash");
                                }
                                // ReSharper disable once EmptyGeneralCatchClause
                                catch (Exception) //Deleting always throws excptions
                                {
                                }
                                finally
                                {
                                    imap.Expunge();
                                }
                            }
                            successful = true;
                        }
                    }
                }
            }

            return Json(new {Result = successful});
        }
Example #16
0
        /// <summary>
        /// Проверка почты 
        /// </summary>
        private void Check_mail()
        {
            //Проверяем доступность почты как таковой
            try
            {
                //Используем методы из библиотеки AE.Net.Mail
                //Создаем коннект на почту
                var imap = new ImapClient("imap.gmail.com", Properties.Settings.Default.Login, Properties.Settings.Default.Password, ImapClient.AuthMethods.Login, 993, true);
                
                //Идем во входящие
                imap.SelectMailbox("INBOX");
                
                //Ищем во входящих все сообщения, которые еще не прочитаны
                var unseenList = imap.SearchMessages(SearchCondition.Unseen());

                //Если такие есть
                if (unseenList.Count() != 0)
                {
                    //Выводим всплывающее окошко в трее о их наличии
                    notifyIcon1.ShowBalloonTip(1000, "Gmail", "Непрочтитанных сообщений - " + unseenList.Count().ToString(), ToolTipIcon.Info);
                }
            }

            //ловим исключение 
            catch (Exception)
            {
                //останавливаем таймер
                timer.Stop();
                
                //Сообщение о недоступности почты
                MessageBox.Show("Не могу зайти на почту, проверьте настройки.");
                
                //Запускаем метод создания формы настроек
                Settings_form();
            }

        }
Example #17
0
        private void rSSEmailToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (rSSEmailToolStripMenuItem.Checked == false)
            {
                try
                {
                    emailuser = txt_emailuser.Text;
                    emailpass = txt_emailpass.Text;
                    ImapClient ic = new ImapClient("imap.gmail.com", emailuser, emailpass,
                                    ImapClient.AuthMethods.Login, 993, true);
                    ic.SelectMailbox("INBOX");
                    MailMessage[] mm = ic.GetMessages(0, ic.GetMessageCount());
                    latestemail = mm[ic.GetMessageCount() - 1].Subject;
                    ic.Dispose();

                    try
                    {
                        switch (cmb_emailtime.SelectedItem.ToString())
                        {
                            case "3 Seconds":
                                tmr_email.Interval = 3000;
                                tmr_email.Enabled = true;
                                break;

                            case "5 Seconds":
                                tmr_email.Interval = 5000;
                                tmr_email.Enabled = true;
                                break;

                            case "10 Seconds":
                                tmr_email.Interval = 10000;
                                tmr_email.Enabled = true;
                                break;

                            case "30 Seconds":
                                tmr_email.Interval = 30000;
                                tmr_email.Enabled = true;
                                break;

                            case "1 Minute":
                                tmr_email.Interval = 60000;
                                tmr_email.Enabled = true;
                                break;

                            case "5 Minutes":
                                tmr_email.Interval = 300000;
                                tmr_email.Enabled = true;
                                break;

                            case "10 Minutes":
                                tmr_email.Interval = 600000;
                                tmr_email.Enabled = true;
                                break;

                            case "30 Minutes":
                                tmr_email.Interval = 1800000;
                                tmr_email.Enabled = true;
                                break;

                            case "1 Hour":
                                tmr_email.Interval = 3600000;
                                tmr_email.Enabled = true;
                                break;

                            default:
                                tmr_email.Interval = 10000;
                                tmr_email.Enabled = true;
                                break;
                        }
                    }
                    catch
                    {
                        tmr_email.Interval = 10000;
                        tmr_email.Enabled = true;
                    }

                    rSSEmailToolStripMenuItem.Checked = true;
                }
                catch { }
            }
            else
            {
                tmr_email.Enabled = false;
                rSSEmailToolStripMenuItem.Checked = false;
            }
        }
Example #18
0
        private void tmr_email_Tick(object sender, EventArgs e)
        {
            try
            {
                ImapClient ic = new ImapClient("imap.gmail.com", emailuser, emailpass,
                                    ImapClient.AuthMethods.Login, 993, true);
                ic.SelectMailbox("INBOX");
                MailMessage[] mm = ic.GetMessages(0, ic.GetMessageCount());
                if (mm[ic.GetMessageCount() - 1].Subject != latestemail)
                {
                    latestemail = mm[ic.GetMessageCount() - 1].Subject;
                    emailstrip.DropDownItems.Add(latestemail);
                    Notification frmOut = new Notification();
                    frmOut.Set_Text(mm[ic.GetMessageCount() - 1].Subject);
                    frmOut.Show();
                }

                ic.Dispose();
            }
            catch { }
        }
        //Metode for å hente inn mail
        public static void mottaMail()
        {
            ImapClient ic = null;
            try
            {
                //Lager nytt objekt av klassen ImapClient
                ic = new ImapClient(host, sendMail.email, sendMail.password,
                     ImapClient.AuthMethods.Login, port, secure);
                ic.SelectMailbox("INBOX");

                //Array som henter inn alle mail i innboksen
                MailMessage[] mail = ic.GetMessages(0, 1, false, true);

                //If-setning som sjekker om det er mail i innboksen
                if (mail.Length != 0)
                {
                    //Tre variabler som henter ut informasjon fra den siste motatte mailen
                    from = mail[mail.Length - 1].From.Address;

                    //Løkke med if-setning som sjekker om mailen er lagt til i databasen
                    foreach (DataRow dtRow in GUI_FORM.dtEmails.Rows)
                    {
                        if (from == dtRow["Adresser"].ToString())
                        {
                            subject = mail[mail.Length - 1].Subject;
                            body = mail[mail.Length - 1].Body;
                        }

                    }
                    //Løkke som sletter alle mail etter den har hentet inn den siste
                    foreach (MailMessage m in mail) ic.DeleteMessage(m);

                }
                warningSentMotta = false;
            }
            catch (Exception ex)
            {
                if (warningSentMotta == false)
                {
                    warningSentMotta = true; //Unngår spam
                    Logger.Error(ex, module);
                }
            }
            finally
            {
                if (ic != null) ic.Dispose();
            }
        }
Example #20
0
 private void currentEmailNotificationToolStripMenuItem_Click(object sender, EventArgs e)
 {
     try
     {
         emailuser = txt_emailuser.Text;
         emailpass = txt_emailpass.Text;
         emailstrip.DropDownItems.Clear();
         ImapClient ic = new ImapClient("imap.gmail.com", emailuser, emailpass,
                         ImapClient.AuthMethods.Login, 993, true);
         ic.SelectMailbox("INBOX");
         MailMessage[] mm = ic.GetMessages(0, ic.GetMessageCount());
         foreach (MailMessage m in mm)
         {
             emailstrip.DropDownItems.Add(m.Subject);
         }
         ic.Dispose();
     }
     catch { }
 }
Example #21
0
        //public bool ConnectPop3(string server, int port, string username, string password)
        //{
        //    try
        //    {
        //        this._popCLient = new POPClient(server, 110, username, password, AuthenticationMethod.USERPASS);
        //        this._popCLient.ReceiveTimeOut = 10000000;
        //    }
        //    catch (Exception e)
        //    {
        //        return false;
        //    }
        //    return true;
        //}
        public bool ConnectIMAP(string server, int port, string username, string password)
        {
            this._port = port;
            this._username = username;
            this._server = server;
            this._password = password;

            try
            {
                ic = new ImapClient(server, username, password, AuthMethods.Login, port, true);
                ic.SelectMailbox("INBOX");
                return true;
            }
            catch (Exception)
            {
                this.CloseConnection();
                return false;
            }
        }
Example #22
0
 private static MailMessage GetLastMessageFromInBox(string testAccountName,string testAccountPassword,string folderName="INBOX")
 {
     // Connect to the IMAP server. 
     MailMessage message = null;
     Console.WriteLine(EnvironmentSettings.TestAccountName);
     Console.WriteLine(EnvironmentSettings.TestAccountPassword);
     using (ImapClient ic = new ImapClient(EnvironmentSettings.TestEmailServerHost, EnvironmentSettings.TestAccountName, EnvironmentSettings.TestAccountPassword,
                     ImapClient.AuthMethods.Login, 993, true))
     {
         // Select folder and get the last mail.
         ic.SelectMailbox(folderName);
         message= ic.GetMessage(ic.GetMessageCount() - 1);
                        
     }
     return message;
 }
Example #23
0
        public JsonResult GetMail(int? timezoneOffset, bool showUnreadOnly, bool showPreview, string folderName)
        {
            var successful = false;
            var output = new List<GmailThread>();
            var unreadCount = 0;
            var folders = new List<string>();

            if (Request.IsAuthenticated)
            {
                using (var uow = new UnitOfWork(GlobalConfig.ConnectionString))
                {
                    var user = uow.UserRepository.GetUserByUsername(User.Identity.Name);

                    if (DateTime.Compare(DateTime.Now, user.OAuthAccessTokenExpiration) < 0)
                    {
                        using (
                            var imap = new ImapClient("imap.gmail.com", user.EmailAddress,
                                user.CurrentOAuthAccessToken, AuthMethods.SaslOAuth, 993, true,
                                true))
                        {
                            imap.SelectMailbox(folderName);

                            var listMailboxes = imap.ListMailboxes(string.Empty, "*");

                            foreach (var listMailbox in listMailboxes)
                            {
                                if (!listMailbox.Name.StartsWith("[Gmail]") &&
                                    String.Compare(listMailbox.Name, folderName, StringComparison.OrdinalIgnoreCase) != 0)
                                {
                                    folders.Add(listMailbox.Name);
                                }
                            }

                            var searchCondition = SearchCondition.Undeleted();
                            if (showUnreadOnly)
                            {
                                searchCondition = searchCondition.And(SearchCondition.Unseen());
                            }

                            //Get messages and organize into threads

                            var uidCollection = imap.Search(searchCondition);

                            var messages = new List<GmailMessage>();
                            foreach (var uid in uidCollection)
                            {
                                var cacheKey = "gmail_" + uid + (showPreview ? "_WPrev" : "");
                                var mailMessageBytes = HttpContext.Cache.Get(cacheKey) as byte[];
                                if (mailMessageBytes == null)
                                {
                                    var mailMessage = new GmailMessage(imap.GetMessage(uid, !showPreview, false));
                                    var encryptedMessage = GlobalConfig.Encryptor.EncryptString(JsonConvert.SerializeObject(mailMessage));
                                    HttpContext.Cache.Insert(cacheKey, encryptedMessage);
                                    messages.Add(mailMessage);
                                }
                                else
                                {
                                    var decryptedMessage = GlobalConfig.Encryptor.DecryptString(mailMessageBytes);
                                    var mailMessage = JsonConvert.DeserializeObject<GmailMessage>(decryptedMessage);
                                    messages.Add(mailMessage);
                                }
                            }
                            var threads = new Dictionary<long, GmailMessage>();
                            var threadMessages = new Dictionary<long, List<long>>();
                            var threadCounts = new Dictionary<long, int>();
                            foreach (var m in messages.OrderByDescending(m => m.MessageDate))
                            {
                                var headers = m.Headers;
                                var gmailThreadId = long.Parse(headers["X-GM-THRID"]);

                                if (!threads.ContainsKey(gmailThreadId))
                                {
                                    threads.Add(gmailThreadId, m);
                                    threadCounts.Add(gmailThreadId, 1);
                                    threadMessages.Add(gmailThreadId, new List<long> {m.Uid});
                                }
                                else
                                {
                                    threadCounts[gmailThreadId] += 1;
                                    threadMessages[gmailThreadId].Add(m.Uid);
                                }
                            }

                            //Bundle threads
                            foreach (var thread in threads)
                            {
                                var messageDate = (thread.Value.MessageDate.Ticks > 0
                                    ? (timezoneOffset.HasValue
                                        ? thread.Value.MessageDate.ToUniversalTime().AddMinutes(timezoneOffset.Value)
                                        : thread.Value.MessageDate.ToUniversalTime())
                                    : new DateTime(1900, 1, 1));
                                var messageDateString = (DateTime.Compare(messageDate.Date, DateTime.Now.Date) == 0
                                    ? messageDate.ToShortTimeString()
                                    : messageDate.ToShortDateString());
                                var unread = !(thread.Value.MessageFlags.HasFlag(GmailMessage.Flags.Seen));
                                if (unread)
                                {
                                    unreadCount++;
                                }
                                output.Add(new GmailThread
                                {
                                    Subject = thread.Value.Subject,
                                    From =
                                        thread.Value.FromDisplayName +
                                        (threadCounts[thread.Key] > 1 ? " (" + threadCounts[thread.Key] + ")" : ""),
                                    ThreadIdHex = thread.Key.ToString("X").ToLower(),
                                    ThreadId = thread.Key,
                                    ThreadMessageIds = string.Join(",", threadMessages[thread.Key].ToArray()),
                                    Date = messageDateString,
                                    Preview = (showPreview ? getPreview(thread.Value.Body) : ""),
                                    Unread = unread,
                                    Important =
                                        (thread.Value.Headers.ContainsKey("X-GM-LABELS") &&
                                         thread.Value.Headers["X-GM-LABELS"].Equals("\"\\\\Important\""))
                                });
                            }
                            successful = true;
                        }
                    }
                }
            }
            return Json(
                new {Result = successful, Data = output, UnreadCount = unreadCount, Folders = folders.ToArray()},
                JsonRequestBehavior.AllowGet);
        }