从Google API获取未读电子邮件

时间:2015-04-16 19:19:02

标签: gmail-api

我正在尝试使用谷歌API获取未读电子邮件的数量,但无法实现。非常感谢您的帮助。我没有收到任何错误,但是计数与gmail中显示的实际数字不匹配。

 try
        {
            String serviceAccountEmail = "xxx@developer.gserviceaccount.com";
            var certificate = new X509Certificate2(@"C:\Projects\xxx\xyz\API Project-xxxxx.p12", "notasecret", X509KeyStorageFlags.Exportable);

            ServiceAccountCredential credential = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                User = "xxx@gmail.com",

                Scopes = new[] { Google.Apis.Gmail.v1.GmailService.Scope.GmailReadonly }
            }.FromCertificate(certificate));


            var gmailservice = new Google.Apis.Gmail.v1.GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "GoogleApi3",
            });

            try
            {                 

                List<Message> lst = ListMessages(gmailservice, "xxx@gmail.com", "IN:INBOX IS:UNREAD");
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
            }
        }
        catch (Exception ex)
        {

        }       

3 个答案:

答案 0 :(得分:3)

您可以使用ListMessages method from the API示例(为完整性而包含)进行搜索:

private static List<Message> ListMessages(GmailService service, String userId, String query)
        {
            List<Message> result = new List<Message>();
            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
            request.Q = query;

            do
            {
                try
                {
                    ListMessagesResponse response = request.Execute();
                    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;
        }

您可以使用此搜索方法查找未读消息,例如:

List<Message> unreadMessageIDs = ListMessages(service, "me", "is:unread");

q参数(查询)可以是各种东西(它与Web界面顶部的gmail搜索栏相同),如下所示:https://support.google.com/mail/answer/7190?hl=en

请注意,您只设置了Message对象的一些参数。如果您想要检索消息,则必须使用GetMessage method from the api

public static Message GetMessage(GmailService service, String userId, String messageId)
  {
      try
      {
          return service.Users.Messages.Get(userId, messageId).Execute();
      }
      catch (Exception e)
      {
          Console.WriteLine("An error occurred: " + e.Message);
      }

      return null;
  }

我同意API不是直截了当的,并且错过了很多功能。

答案 1 :(得分:2)

只需执行:labels.get(id =&#34; INBOX&#34;)并且它具有这些类型的统计信息(该标签中有多少条消息,未读取的数量和线程相同)。

https://developers.google.com/gmail/api/v1/reference/users/labels/get

答案 2 :(得分:0)

.Net解决方案:

    // Get UNREAD messages
    public void getUnreadEmails(GmailService service)
    {            
        UsersResource.MessagesResource.ListRequest Req_messages = service.Users.Messages.List("me");            
        // Filter by labels
        Req_messages.LabelIds = new List<String>() { "INBOX", "UNREAD" };            
        // Get message list
        IList<Message> messages = Req_messages.Execute().Messages;
        if ((messages != null) && (messages.Count > 0))
        {
            foreach (Message List_msg in messages)
            {
                // Get message content
                UsersResource.MessagesResource.GetRequest MsgReq = service.Users.Messages.Get("me", List_msg.Id);
                Message msg = MsgReq.Execute();
                Console.WriteLine(msg.Snippet);
                Console.WriteLine("----------------------");
            }
        }

        Console.Read();
    }