/// <summary>
        /// Reads the messages from label identifier asynchronous.
        /// </summary>
        /// <param name="labelId">The label identifier.</param>
        /// <exception cref="ArgumentException">Label Id is null or empty - labelId</exception>
        private async Task ReadMessagesFromLabelIdAsync(string labelId)
        {
            try
            {
                if (string.IsNullOrEmpty(labelId))
                {
                    throw new ArgumentException($"Label Id is null or empty", nameof(labelId));
                }

                UsersResource.MessagesResource.ListRequest messagesToRead = GoogleServiceHelper.UsersResource.Messages.List(USER_ID);
                messagesToRead.LabelIds         = labelId;
                messagesToRead.IncludeSpamTrash = false;

                var response = await messagesToRead.ExecuteAsync();

                var newEmailExisits = response.Messages != null;

                if (newEmailExisits)
                {
                    await PopulateEmailQueueAndDeleteEmailAsync(response, false);
                }
                else
                {
                    LogDebug($"No new emails from kindle received in the label");
                }
            }
            catch (Exception e)
            {
                LogError(e);
                throw;
            }
        }
示例#2
0
        private async Task <List <Message> > GetMessagesAsync(GmailService service, string[] labels = null, string query = null, string userId = "me")
        {
            List <Message> result = new List <Message>();

            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
            if (labels != null)
            {
                request.LabelIds = labels;
            }
            if (!string.IsNullOrWhiteSpace(query))
            {
                request.Q = query;
            }

            do
            {
                try
                {
                    ListMessagesResponse response = await request.ExecuteAsync();

                    result.AddRange(response.Messages);
                    request.PageToken = response.NextPageToken;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                }
            } while (!string.IsNullOrEmpty(request.PageToken));

            return(result);
        }
示例#3
0
 public int GetINBOX()
 {
     // Define parameter for request
     UsersResource.MessagesResource.ListRequest ThreadRequest = service.Users.Messages.List("me");
     ThreadRequest.LabelIds = "INBOX";
     // Get mail include spam trash?
     ThreadRequest.IncludeSpamTrash = false; // NO
     ThreadRequest.MaxResults       = int.MaxValue;
     // Make a request
     try
     {
         return(ThreadRequest.ExecuteAsync().Result.Messages.Count());
     }
     catch (Exception)
     {
         return(0);
     }
 }
        private async Task <List <Message> > ListMessages(GmailService service, String userId, String query)
        {
            List <Message> result = new List <Message>();

            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
            // disable spam and trash
            request.IncludeSpamTrash = false;
            //choosing INBOX option
            request.LabelIds = "INBOX";
            request.Q        = query;

            do
            {
                ListMessagesResponse response = await request.ExecuteAsync();

                result.AddRange(response.Messages);
                request.PageToken = response.NextPageToken;
            } while (!String.IsNullOrEmpty(request.PageToken));

            return(result);
        }
        public async Task <IEnumerable <Message> > GetMessagesAsync(string query, string email)
        {
            List <Message> result = new List <Message>();

            UsersResource.MessagesResource.ListRequest request = this.emailService.Users.Messages.List(email);
            request.Q = query;

            do
            {
                try
                {
                    ListMessagesResponse response = await request.ExecuteAsync();

                    result.AddRange(response.Messages);
                    request.PageToken = response.NextPageToken;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                }
            } while (!String.IsNullOrEmpty(request.PageToken));

            return(result);
        }
示例#6
0
        public static async Task <List <string[]> > GetEmailsAndScrapeThem(string search,
                                                                           Action <string[]> onAdd)
        {
            var rows = new List <string[]>();

            UsersResource.MessagesResource.ListRequest request =
                GmailService.Users.Messages.List("me");
            request.MaxResults = int.MaxValue;
            request.Q          = search;
            IList <Message> messages = (await request.ExecuteAsync()).Messages;

            if (messages == null || messages.Count <= 0)
            {
                return(rows);
            }
            try
            {
                foreach (Message message in messages)
                {
                    if (Stop)
                    {
                        break;
                    }

                    UsersResource.MessagesResource.GetRequest req =
                        GmailService.Users.Messages.Get("me", message.Id);
                    Message mes = await req.ExecuteAsync();

                    string a;
                    if (!string.IsNullOrEmpty(mes.Payload.Parts[0].Body.Data))
                    {
                        a = mes.Payload.Parts[0].Body.Data;
                    }
                    else if (mes.Payload.Parts[0].Parts[0].Parts != null)
                    {
                        a = mes.Payload.Parts[0].Parts[0].Parts[1].Body.Data;
                    }
                    else
                    {
                        a = mes.Payload.Parts[0].Parts[1].Body.Data;
                    }

                    if (a == null)
                    {
                        continue;
                    }
                    string body    = Utf8.GetString(WebEncoders.Base64UrlDecode(a));
                    var    results = new string[FieldsList.Count];
                    for (var i = 0; i < FieldsList.Count; i++)
                    {
                        FieldToFind f       = FieldsList[i];
                        Match       rcMatch = Regex.Match(body, f.Regex, RegExOptions);
                        if (f.Required && !rcMatch.Success)
                        {
                            results[i] = "NOT FOUND";
                        }
                        else
                        {
                            results[i] = rcMatch.Groups[f.GroupNumber].Value;
                        }
                    }

                    onAdd(results);
                    rows.Add(results);
                }
            }
            catch
            {
                // ignored
            }

            return(rows);
        }
示例#7
0
        public async Task <IList <Message> > ExecuteAsync()
        {
            ListMessagesResponse messagesResponse = await request.ExecuteAsync();

            return(messagesResponse.Messages);
        }
示例#8
0
        /// <summary>
        /// Asynchronous method used to synchronize the user inbox
        /// </summary>
        /// <param name="manual">Indicates if the synchronization come's from the timer tick or has been manually triggered</param>
        /// <param name="token">Indicates if the Gmail token need to be refreshed</param>
        public async void Sync(bool manual = true, bool token = false)
        {
            // prevents the application from syncing the inbox when updating
            if (UI.UpdateService.Updating)
            {
                return;
            }

            // updates the synchronization time
            Time = DateTime.Now;

            // resets reconnection count and prevents the application from displaying continuous warning icon when a timertick synchronization occurs after a reconnection attempt
            if (ReconnectionAttempts != 0)
            {
                manual = true;
                ReconnectionAttempts = 0;
            }

            // disables the timeout when the user do a manual synchronization
            if (manual && UI.NotificationService.Paused)
            {
                UI.NotificationService.Resume();

                return;
            }

            // if internet is down, attempts to reconnect the user mailbox
            if (!UI.ComputerService.IsInternetAvailable())
            {
                UI.timerReconnect.Enabled = true;
                UI.timer.Enabled          = false;

                return;
            }

            // refreshes the token if needed
            if (token)
            {
                await UI.GmailService.RefreshToken();
            }

            // activates the necessary menu items
            UI.menuItemSynchronize.Enabled = true;
            UI.menuItemTimout.Enabled      = true;
            UI.menuItemSettings.Enabled    = true;

            // displays the sync icon, but only on manual synchronization
            if (manual)
            {
                UI.notifyIcon.Icon = Resources.sync;
                UI.notifyIcon.Text = Translation.sync;
            }

            // do a small ping on the update service
            UI.UpdateService.Ping();

            try {
                // initializes the gmail service base client api
                if (Api == null)
                {
                    Api = new GmailService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = UI.GmailService.Credential,
                        ApplicationName       = Settings.Default.APPLICATION_NAME
                    });

                    // retrieves the gmail address
                    UI.labelEmailAddress.Text = EmailAddress = Api.Users.GetProfile("me").Execute().EmailAddress;
                }

                // manages the spam notification
                if (Settings.Default.SpamNotification)
                {
                    // exits if a spam is already detected
                    if (!manual && UI.NotificationService.Tag == "#spam")
                    {
                        return;
                    }

                    // gets the "spam" label
                    Label spam = await Api.Users.Labels.Get("me", "SPAM").ExecuteAsync();

                    // manages unread spams
                    if (spam.ThreadsUnread > 0)
                    {
                        // plays a sound on unread spams
                        if (Settings.Default.AudioNotification)
                        {
                            SystemSounds.Exclamation.Play();
                        }

                        // displays a balloon tip in the systray with the total of unread threads
                        UI.NotificationService.Tip(spam.ThreadsUnread.ToString() + " " + (spam.ThreadsUnread > 1 ? Translation.unreadSpams : Translation.unreadSpam), Translation.newUnreadSpam, Notification.Type.Error);

                        // sets the notification icon and text
                        UI.notifyIcon.Icon = Resources.spam;
                        UI.notifyIcon.Text = spam.ThreadsUnread.ToString() + " " + (spam.ThreadsUnread > 1 ? Translation.unreadSpams : Translation.unreadSpam);

                        // updates the tag
                        UI.NotificationService.Tag = "#spam";

                        return;
                    }
                }

                // gets the "inbox" label
                Box = await Api.Users.Labels.Get("me", "INBOX").ExecuteAsync();

                // updates the statistics
                UpdateStatistics();

                // exits the sync if the number of unread threads is the same as before
                if (!manual && (Box.ThreadsUnread == UnreadThreads))
                {
                    return;
                }

                // manages unread threads
                if (Box.ThreadsUnread > 0)
                {
                    // sets the notification icon
                    UI.notifyIcon.Icon = Box.ThreadsUnread <= Settings.Default.UNSTACK_BOUNDARY ? Resources.mails : Resources.stack;

                    // manages message notification
                    if (Settings.Default.MessageNotification)
                    {
                        // plays a sound on unread threads
                        if (Settings.Default.AudioNotification)
                        {
                            SystemSounds.Asterisk.Play();
                        }

                        // gets the message details
                        UsersResource.MessagesResource.ListRequest messages = Api.Users.Messages.List("me");
                        messages.LabelIds   = "UNREAD";
                        messages.MaxResults = 1;
                        Google.Apis.Gmail.v1.Data.Message message = await Api.Users.Messages.Get("me", await messages.ExecuteAsync().ContinueWith(m => {
                            return(m.Result.Messages.First().Id);
                        })).ExecuteAsync();

                        //  displays a balloon tip in the systray with the total of unread threads and message details, depending on the user privacy setting
                        if (Box.ThreadsUnread == 1 && Settings.Default.PrivacyNotification != (int)Notification.Privacy.All)
                        {
                            string subject = "";
                            string from    = "";

                            foreach (MessagePartHeader header in message.Payload.Headers)
                            {
                                if (header.Name == "Subject")
                                {
                                    subject = header.Value != "" ? header.Value : Translation.newUnreadMessage;
                                }
                                else if (header.Name == "From")
                                {
                                    Match match = Regex.Match(header.Value, ".* <");

                                    if (match.Length != 0)
                                    {
                                        from = match.Captures[0].Value.Replace(" <", "").Replace("\"", "");
                                    }
                                    else
                                    {
                                        match = Regex.Match(header.Value, "<?.*>?");
                                        from  = match.Length != 0 ? match.Value.ToLower().Replace("<", "").Replace(">", "") : header.Value.Replace(match.Value, Box.ThreadsUnread.ToString() + " " + Translation.unreadMessage);
                                    }
                                }
                            }

                            if (Settings.Default.PrivacyNotification == (int)Notification.Privacy.None)
                            {
                                subject = message.Snippet != "" ? WebUtility.HtmlDecode(message.Snippet) : Translation.newUnreadMessage;
                            }

                            // detects if the message contains attachments
                            if (message.Payload.Parts != null && message.Payload.MimeType == "multipart/mixed")
                            {
                                int attachments = message.Payload.Parts.Where(part => !String.IsNullOrEmpty(part.Filename)).Count();

                                if (attachments > 0)
                                {
                                    from = (from.Length > 48 ? from.Substring(0, 48) : from) + " – " + attachments.ToString() + " " + (attachments > 1 ? Translation.attachments : Translation.attachment);
                                }
                            }

                            UI.NotificationService.Tip(from, subject);
                        }
                        else
                        {
                            UI.NotificationService.Tip(Box.ThreadsUnread.ToString() + " " + (Box.ThreadsUnread > 1 ? Translation.unreadMessages : Translation.unreadMessage), Translation.newUnreadMessage);
                        }

                        // updates the notification tag to allow the user to directly display the specified view (inbox/message/spam) in a browser
                        UI.NotificationService.Tag = "#inbox" + (Box.ThreadsUnread == 1 ? "/" + message.Id : "");
                    }

                    // displays the notification text
                    UI.notifyIcon.Text = Box.ThreadsUnread.ToString() + " " + (Box.ThreadsUnread > 1 ? Translation.unreadMessages : Translation.unreadMessage);

                    // enables the mark as read menu item
                    UI.menuItemMarkAsRead.Text    = Translation.markAsRead + " (" + Box.ThreadsUnread + ")";
                    UI.menuItemMarkAsRead.Enabled = true;
                }
                else
                {
                    // restores the default systray icon and text
                    UI.notifyIcon.Icon = Resources.normal;
                    UI.notifyIcon.Text = Translation.noMessage;

                    // disables the mark as read menu item
                    UI.menuItemMarkAsRead.Text    = Translation.markAsRead;
                    UI.menuItemMarkAsRead.Enabled = false;
                }

                // saves the number of unread threads
                UnreadThreads = Box.ThreadsUnread;
            } catch (Exception exception) {
                // displays a balloon tip in the systray with the detailed error message
                UI.notifyIcon.Icon = Resources.warning;
                UI.notifyIcon.Text = Translation.syncError;
                UI.NotificationService.Tip(Translation.error, Translation.syncErrorOccured + exception.Message, Notification.Type.Warning, 1500);
            } finally {
                UI.notifyIcon.Text = UI.notifyIcon.Text.Split('\n')[0] + "\n" + Translation.syncTime.Replace("{time}", Time.ToLongTimeString());
            }
        }
示例#9
0
        /// <summary>
        /// Asynchronous method used to mark as read the user inbox
        /// </summary>
        public async void MarkAsRead()
        {
            try {
                // updates the synchronization time
                Time = DateTime.Now;

                // displays the sync icon
                UI.notifyIcon.Icon = Resources.sync;
                UI.notifyIcon.Text = Translation.sync;

                // gets all unread messages
                UsersResource.MessagesResource.ListRequest messages = Api.Users.Messages.List("me");
                messages.LabelIds = "UNREAD";
                ListMessagesResponse list = await messages.ExecuteAsync();

                IList <Message> unread = list.Messages;

                // loops through all unread threads and removes the "unread" label for each one
                if (unread != null && unread.Count > 0)
                {
                    // batch all mail ids to modify
                    IEnumerable <string> batch = unread.Select(
                        thread => thread.Id
                        );

                    // creates the batch request
                    BatchModifyMessagesRequest request = new BatchModifyMessagesRequest()
                    {
                        Ids            = batch.ToList(),
                        RemoveLabelIds = new List <string>()
                        {
                            "UNREAD"
                        }
                    };

                    // executes the batch request to mark all mails as read
                    await Api.Users.Messages.BatchModify(request, "me").ExecuteAsync();

                    // gets the "inbox" label
                    Box = await Api.Users.Labels.Get("me", "INBOX").ExecuteAsync();

                    // updates the statistics
                    UpdateStatistics();
                }

                // restores the default systray icon and text
                UI.notifyIcon.Icon = Resources.normal;
                UI.notifyIcon.Text = Translation.noMessage;

                // cleans the tag
                UI.NotificationService.Tag = null;

                // resets the number of unread threads
                UnreadThreads = 0;

                // disables the mark as read menu item
                UI.menuItemMarkAsRead.Text    = Translation.markAsRead;
                UI.menuItemMarkAsRead.Enabled = false;
            } catch (Exception exception) {
                // enabled the mark as read menu item
                UI.menuItemMarkAsRead.Text    = Translation.markAsRead + " (" + Box.ThreadsUnread + ")";
                UI.menuItemMarkAsRead.Enabled = true;

                // displays a balloon tip in the systray with the detailed error message
                UI.notifyIcon.Icon = Resources.warning;
                UI.notifyIcon.Text = Translation.markAsReadError;
                UI.NotificationService.Tip(Translation.error, Translation.markAsReadErrorOccured + exception.Message, Notification.Type.Warning, 1500);
            } finally {
                UI.notifyIcon.Text = UI.notifyIcon.Text.Split('\n')[0] + "\n" + Translation.syncTime.Replace("{time}", Time.ToLongTimeString());
            }
        }