private async Task <List <PersonModel> > GetGooglePeopleAsync()
        {
            try
            {
                PeopleResource.ConnectionsResource.ListRequest peopleRequest = service.People.Connections.List("people/me");
                peopleRequest.RequestMaskIncludeField = "person.emailAddresses,person.names,person.photos";

                ListConnectionsResponse connectionsResponse = await((IClientServiceRequest <ListConnectionsResponse>)peopleRequest).ExecuteAsync();
                IList <Person>          connections         = connectionsResponse.Connections;
                List <PersonModel>      result = new List <PersonModel>();
                if (connections != null && connections.Count > 0)
                {
                    foreach (var people in connections)
                    {
                        if (people != null)
                        {
                            result.Add(new PersonModel(people));
                        }
                    }
                }

                return(result);
            }
            catch (GoogleApiException ex)
            {
                throw GoogleClient.HandleGoogleAPIException(ex);
            }
        }
        // get people work with
        public async Task <List <PersonModel> > GetPeopleAsync(string name)
        {
            try
            {
                List <PersonModel> persons = null;
                if (this.cachedPeople != null)
                {
                    persons = this.cachedPeople;
                }
                else
                {
                    persons = await GetGooglePeopleAsync();
                }

                List <PersonModel> result = new List <PersonModel>();
                foreach (var person in persons)
                {
                    // filter manually
                    var displayName = person.DisplayName;
                    if (person.Emails?.Count > 0 && displayName != null && displayName.ToLower().Contains(name.ToLower()))
                    {
                        result.Add(person);
                    }
                }

                this.cachedPeople = result;
                return(result);
            }
            catch (GoogleApiException ex)
            {
                throw GoogleClient.HandleGoogleAPIException(ex);
            }
        }
 public async Task DeleteMessageAsync(string id)
 {
     try
     {
         var deleteRequest = service.Users.Messages.Delete(
             "me", id);
         await((IClientServiceRequest <string>)deleteRequest).ExecuteAsync();
     }
     catch (GoogleApiException ex)
     {
         throw GoogleClient.HandleGoogleAPIException(ex);
     }
 }
        public async Task MarkMessageAsReadAsync(string id)
        {
            try
            {
                var mods           = new ModifyMessageRequest();
                var labelsToRemove = new List <string>()
                {
                    "UNREAD"
                };
                mods.RemoveLabelIds = labelsToRemove;

                var updateRequest = service.Users.Messages.Modify(
                    mods, "me", id);
                await((IClientServiceRequest <GmailMessage>)updateRequest).ExecuteAsync();
            }
            catch (GoogleApiException ex)
            {
                throw GoogleClient.HandleGoogleAPIException(ex);
            }
        }
        public async Task <PersonModel> GetMeAsync()
        {
            try
            {
                var peopleRequest = service.People.Get("people/me");
                peopleRequest.RequestMaskIncludeField = "person.emailAddresses,person.names,person.photos";

                var me = await peopleRequest.ExecuteAsync();

                if (me != null)
                {
                    return(new PersonModel(me));
                }

                return(null);
            }
            catch (GoogleApiException ex)
            {
                throw GoogleClient.HandleGoogleAPIException(ex);
            }
        }
        public async Task SendMessageAsync(string content, string subject, List <Recipient> recipients)
        {
            try
            {
                // get from address
                var profileRequest = service.Users.GetProfile("me");
                var user           = ((IClientServiceRequest <Profile>)profileRequest).Execute();
                var mess           = new MailMessage
                {
                    Subject = subject,
                    From    = new MailAddress(user.EmailAddress)
                };

                foreach (var re in recipients)
                {
                    mess.To.Add(new MailAddress(re.EmailAddress.Address));
                }

                mess.ReplyToList.Add(new MailAddress(user.EmailAddress));
                var adds = AlternateView.CreateAlternateViewFromString(content, new System.Net.Mime.ContentType("text/plain"));
                adds.ContentType.CharSet = Encoding.UTF8.WebName;
                mess.AlternateViews.Add(adds);

                var mime        = MimeMessage.CreateFromMailMessage(mess);
                var sendRequest = service.Users.Messages.Send(
                    new GmailMessage()
                {
                    Raw = Base64UrlEncode(mime.ToString()),
                }, "me");
                await((IClientServiceRequest <GmailMessage>)sendRequest).ExecuteAsync();
            }
            catch (GoogleApiException ex)
            {
                throw GoogleClient.HandleGoogleAPIException(ex);
            }
        }
        public async Task <List <MSMessage> > GetMyMessagesAsync(DateTime fromTime, DateTime toTime, bool getUnRead = false, bool isImportant = false, bool directlyToMe = false, string fromAddress = null)
        {
            try
            {
                var profileRequest = service.Users.GetProfile("me");
                var user           = ((IClientServiceRequest <Profile>)profileRequest).Execute();
                var userAddress    = user.EmailAddress;

                var searchOperation = string.Empty;
                searchOperation = this.AppendFilterString(searchOperation, "in:inbox");
                if (getUnRead)
                {
                    searchOperation = this.AppendFilterString(searchOperation, "is:unread");
                }

                if (isImportant)
                {
                    searchOperation = this.AppendFilterString(searchOperation, "is:important");
                }

                if (directlyToMe)
                {
                    searchOperation = this.AppendFilterString(searchOperation, $"deliveredto:{userAddress}");
                }

                if (fromAddress != null)
                {
                    searchOperation = this.AppendFilterString(searchOperation, $"from:{fromAddress}");
                }

                if (fromTime != null)
                {
                    searchOperation = this.AppendFilterString(searchOperation, $"after:{GetUnixTime(fromTime)}");
                }

                if (toTime != null)
                {
                    searchOperation = this.AppendFilterString(searchOperation, $"before:{GetUnixTime(toTime)}");
                }

                var request = service.Users.Messages.List("me");
                request.Q          = searchOperation;
                request.MaxResults = this.maxSize;

                var response = await((IClientServiceRequest <ListMessagesResponse>)request).ExecuteAsync();
                var result   = new List <MSMessage>();

                // response.Messages only have id and threadID
                if (response.Messages != null)
                {
                    var messages = await Task.WhenAll(response.Messages.Select(temp =>
                    {
                        var req    = service.Users.Messages.Get("me", temp.Id);
                        req.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Raw;
                        return(((IClientServiceRequest <GmailMessage>)req).ExecuteAsync());
                    }));

                    if (messages != null && messages.Length > 0)
                    {
                        foreach (var m in messages)
                        {
                            // map to msgraph email
                            var ms = this.MapMimeMessageToMSMessage(DecodeToMessage(m.Raw));
                            ms.BodyPreview = m.Snippet;
                            ms.Id          = m.Id;
                            ms.WebLink     = $"https://mail.google.com/mail/#inbox/{m.Id}";
                            result.Add(ms);
                        }
                    }
                }

                if (response.NextPageToken != null && response.NextPageToken != string.Empty)
                {
                    this.pageToken = response.NextPageToken;
                }
                else
                {
                    this.pageToken = string.Empty;
                }

                return(result);
            }
            catch (GoogleApiException ex)
            {
                throw GoogleClient.HandleGoogleAPIException(ex);
            }
        }
        public async Task <List <MSMessage> > ReplyToMessageAsync(string id, string content)
        {
            try
            {
                var(originMessage, threadId) = await this.GetMessageById(id);

                var reply = new MimeMessage();

                // reply to the sender of the message
                if (originMessage.ReplyTo.Count > 0)
                {
                    reply.To.AddRange(originMessage.ReplyTo);
                }
                else if (originMessage.From.Count > 0)
                {
                    reply.To.AddRange(originMessage.From);
                }
                else if (originMessage.Sender != null)
                {
                    reply.To.Add(originMessage.Sender);
                }

                // set the reply subject
                if (!originMessage.Subject.StartsWith(EmailCommonStrings.Reply, StringComparison.OrdinalIgnoreCase))
                {
                    reply.Subject = string.Format(EmailCommonStrings.ReplyReplyFormat, originMessage.Subject);
                }
                else
                {
                    reply.Subject = originMessage.Subject;
                }

                // construct the In-Reply-To and References headers
                if (!string.IsNullOrEmpty(originMessage.MessageId))
                {
                    reply.InReplyTo = originMessage.MessageId;
                    foreach (var mid in originMessage.References)
                    {
                        reply.References.Add(mid);
                    }

                    reply.References.Add(originMessage.MessageId);
                }

                // quote the original message text
                using (var quoted = new StringWriter())
                {
                    var sender = originMessage.Sender ?? originMessage.From.Mailboxes.FirstOrDefault();
                    quoted.WriteLine(EmailCommonStrings.EmailInfoFormat, originMessage.Date.ToString("f"), !string.IsNullOrEmpty(sender.Name) ? sender.Name : sender.Address);
                    using (var reader = new StringReader(originMessage.TextBody))
                    {
                        string line;

                        while ((line = reader.ReadLine()) != null)
                        {
                            quoted.Write("> ");
                            quoted.WriteLine(line);
                        }
                    }

                    content = quoted.ToString();
                }

                var sendRequest = service.Users.Messages.Send(
                    new GmailMessage()
                {
                    Raw      = Base64UrlEncode(reply.ToString() + content),
                    ThreadId = threadId,
                }, "me");
                await((IClientServiceRequest <GmailMessage>)sendRequest).ExecuteAsync();
                return(null);
            }
            catch (GoogleApiException ex)
            {
                throw GoogleClient.HandleGoogleAPIException(ex);
            }
        }
        /// <inheritdoc/>
        public async Task ForwardMessageAsync(string id, string content, List <Recipient> recipients)
        {
            try
            {
                // getOriginalMessage
                var(originalMessage, threadId) = await this.GetMessageById(id);

                var forward = new MimeMessage();
                foreach (var recipient in recipients)
                {
                    forward.To.Add(new MailboxAddress(recipient.EmailAddress.Address));
                }

                // set the reply subject
                forward.Subject = string.Format(EmailCommonStrings.ForwardReplyFormat, originalMessage.Subject);

                // construct the References headers
                foreach (var mid in originalMessage.References)
                {
                    forward.References.Add(mid);
                }

                if (!string.IsNullOrEmpty(originalMessage.MessageId))
                {
                    forward.References.Add(originalMessage.MessageId);
                }

                // quote the original message text
                using (var quoted = new StringWriter())
                {
                    var sender = originalMessage.Sender ?? originalMessage.From.Mailboxes.FirstOrDefault();
                    quoted.WriteLine(content);
                    quoted.WriteLine();
                    quoted.WriteLine(EmailCommonStrings.ForwardMessage);
                    quoted.WriteLine(EmailCommonStrings.FromFormat, originalMessage.From);
                    quoted.WriteLine(EmailCommonStrings.DateFormat, originalMessage.Date);
                    quoted.WriteLine(EmailCommonStrings.SubjectFormat, originalMessage.Subject);
                    quoted.WriteLine(EmailCommonStrings.ToFormat, originalMessage.To);
                    if (originalMessage.Cc.Count > 0)
                    {
                        quoted.WriteLine(EmailCommonStrings.CCFormat, originalMessage.Cc);
                    }

                    using (var reader = new StringReader(originalMessage.TextBody))
                    {
                        string line;

                        while ((line = reader.ReadLine()) != null)
                        {
                            quoted.Write("> ");
                            quoted.WriteLine(line);
                        }
                    }

                    content = quoted.ToString();
                }

                var sendRequest = service.Users.Messages.Send(
                    new GmailMessage()
                {
                    Raw      = Base64UrlEncode(forward.ToString() + content),
                    ThreadId = threadId,
                }, "me");
                await((IClientServiceRequest <GmailMessage>)sendRequest).ExecuteAsync();
            }
            catch (GoogleApiException ex)
            {
                throw GoogleClient.HandleGoogleAPIException(ex);
            }
        }