提问者:小点点

只能阅读5条Gmail消息GmailAPI


我正在为我的项目制作一个小的视窗应用程序。我遵循谷歌的文档和这个论坛上的一些人写了一个方法来阅读我的Gmail的“INBOX”中的所有Gmail邮件。我可以在它的正文部分收到Gmail邮件,但我只能收到5封电子邮件,而不是我所有的电子邮件。我试图使用属性“MaxResult”来设置我想收到的最大电子邮件,但什么也没发生。

这是我的方法:

 private async Task GetMAILs()
    {
        try
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows for read-only access to the authenticated 
                    // user's account, but not other types of account access.
                    new[] { GmailService.Scope.GmailReadonly, GmailService.Scope.MailGoogleCom, GmailService.Scope.GmailModify },
                    "an thanh",
                    CancellationToken.None,
                    new FileDataStore(this.GetType().ToString())
                );
            }

            var gmailService = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = this.GetType().ToString()
            });


            //var request = new UsersResource.MessagesResource.ListRequest(gmailService, "me");

            var emailListRequest = gmailService.Users.Messages.List("mymail@gmail.com");
            emailListRequest.LabelIds = "INBOX";
            //emailListRequest.IncludeSpamTrash = false;
            emailListRequest.Q = "in:unread in:inbox"; 
            emailListRequest.MaxResults = 100;

            //get our emails
            var emailListResponse = await emailListRequest.ExecuteAsync();

            if (emailListResponse != null && emailListResponse.Messages != null)
            {
                //loop through each email and get what fields you want...
                foreach (var email in emailListResponse.Messages)
                {
                    //FORM.MessageBox.Show(email.Id);
                    //var request = new UsersResource.MessagesResource.ListRequest(gmailService, "me");
                    //IList<Message> messages = request.Execute().Messages;
                    string from = "";
                    string date = "";
                    string subject = "";
                    string decoded = "";


                    var emailInfoRequest = gmailService.Users.Messages.Get("mymail@gmail.com",email.Id);
                    //make another request for that email id...
                    var emailInfoResponse = await emailInfoRequest.ExecuteAsync();

                    if (emailInfoResponse != null)
                    {

                        //loop through the headers and get the fields we need...
                        foreach (var mParts in emailInfoResponse.Payload.Headers)
                        {
                            if (mParts.Name == "Date")
                            {
                                date = mParts.Value;
                            }
                            else if (mParts.Name == "From")
                            {
                                from = mParts.Value;
                            }
                            else if (mParts.Name == "Subject")
                            {
                                subject = mParts.Value;
                            }
                        }

                        foreach (var ms_part in emailInfoResponse.Payload.Parts)
                        {
                                if (ms_part.MimeType == "text/plain")
                                {
                                    byte[] data = FromBase64ForUrlString(ms_part.Body.Data);
                                    decoded = Encoding.UTF8.GetString(data);
                                }
                        }
                    }
                    bd.AppendLine(string.Format("Từ: {0}", from));
                    bd.AppendLine(subject);
                    bd.AppendLine(date);
                    bd.AppendLine("Content: ");
                    bd.AppendLine(decoded);
                    bd.AppendLine("-------End-------");
                    bd.AppendLine("----------------------------------------------------");
                    //now you have the data you want....
                    richTextBox1.Text = bd.ToString();
                }

            }

        }
        catch (Exception ex)
        {
            FORM.MessageBox.Show("Failed to get messages!: " + ex.Message, "Failed Messages!", FORM.MessageBoxButtons.OK);

        }
    }

将二进制数据转换为字符串的方法:

 public byte[] FromBase64ForUrlString(string base64ForUrlInput)
    {
        int padChars = (base64ForUrlInput.Length % 4) == 0 ? 0 : (4 - (base64ForUrlInput.Length % 4));
        StringBuilder result = new StringBuilder(base64ForUrlInput, base64ForUrlInput.Length + padChars);
        result.Append(String.Empty.PadRight(padChars, '='));
        result.Replace('-', '+');
        result.Replace('_', '/');
        return Convert.FromBase64String(result.ToString());
    }

调用任务“GetMAILs()”的方法:

 private void btGet_Click(object sender, EventArgs e)
    {
        Test2();
    }
    private async void Test2()
    {
        await GetMAILs();
    }

对不起,我只是一个GmailAPI的新生。我将感谢每个人的任何帮助。


共2个答案

匿名用户

一定是您的过滤器有问题。您可以从删除这一行开始:

  emailListRequest.Q = "in:unread in:inbox"; 

或将其更改为:

emailListRequest.Q = "in:inbox"; 

似乎工作时,我用它在用户的消息:列表试用。

匿名用户

试着改成这样:

emailListRequest.Q = "is:unread label:INBOX"

我也尝试了一些东西和这项工作。你也可以使用这个链接通过gmail查看参数API