简体   繁体   English

只能读取5条Gmail邮件Gmail API

[英]Only can read 5 gmail messages Gmail API

I'm making a small Windows Application for my project. 我正在为我的项目制作一个小型Windows应用程序。 I followed the document of Google and some people in this forum to write a method to read all Gmail messages in "INBOX" of my Gmail. 我按照Google和这个论坛中的一些人的文档编写了一种读取我Gmail的“收件箱”中所有Gmail邮件的方法。 I could get Gmail messages in its body part but I just could get 5 emails instead of all of my email messages. 我可以在其正文部分收到Gmail邮件,但仅收到5封电子邮件,而不是我的所有电子邮件。 I tried to use the property "MaxResult" to set maximum emails that I wanted to get but nothing happened. 我尝试使用属性“ MaxResult”设置希望获取的最大电子邮件数量,但没有任何反应。

This is my method: 这是我的方法:

 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);

        }
    }

Method to convert Binary data to String: 将二进制数据转换为字符串的方法:

 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());
    }

Method to call Task "GetMAILs()": 调用任务“ GetMAILs()”的方法:

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

Sorry I'm just a freshman with Gmail API. 抱歉,我只是Gmail API的新生。 I'll be grateful for anyhelp from everyone. 谢谢大家的帮助。

Must be an issue with your filters. 筛选器一定有问题。 You can start by removing this line: 您可以先删除以下行:

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

or change it to: 或将其更改为:

emailListRequest.Q = "in:inbox"; 

Seems to work when I used it in Users.messages: list Try-it . 当我在Users.messages中使用它时,它似乎可以工作:列出Try-it

Try to change to this: 尝试更改为此:

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

I also try something and this work. 我也尝试一些工作。 You also may use this link to see params alow by gmail API 您还可以使用此链接查看gmail API下的参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM