【问题标题】:Only can read 5 gmail messages Gmail API只能读取 5 条 Gmail 邮件 Gmail API
【发布时间】:2018-06-22 15:16:14
【问题描述】:

我正在为我的项目制作一个小型 Windows 应用程序。我按照谷歌和这个论坛的一些人的文档写了一个方法来读取我的Gmail“收件箱”中的所有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();
    }

抱歉,我只是 Gmail API 的大一新生。我会感谢大家的任何帮助。

【问题讨论】:

    标签: c# gmail-api


    【解决方案1】:

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

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

    或将其更改为:

    emailListRequest.Q = "in:inbox"; 
    

    当我在 Users.messages 中使用它时似乎可以工作:list Try-it

    【讨论】:

    • 感谢您的回复。我尝试使用 emailListRequest.Q = "in:inbox"。但我还有 5 封电子邮件。
    • 我只想获取“收件箱”中每个页面的所有电子邮件
    【解决方案2】:

    试着改成这样:

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

    我也尝试了一些东西并且这项工作。您也可以使用此link 查看 gmail API 的参数

    【讨论】:

    • 欢迎提供指向解决方案的链接,但请确保您的答案在没有它的情况下有用:在链接周围添加上下文,以便您的用户了解它是什么以及它存在的原因,然后引用最多如果目标页面不可用,您链接到的页面的相关部分。
    猜你喜欢
    • 2016-07-07
    • 2017-12-19
    • 1970-01-01
    • 2020-06-21
    • 2017-07-27
    • 2020-04-28
    • 2016-11-30
    • 1970-01-01
    相关资源
    最近更新 更多