Warm tip: This article is reproduced from stackoverflow.com, please click
.net c# gmail-api

Get messages which contain an attachment via gmail API

发布于 2020-03-29 12:47:44

I'm building an app based on the Gmail API. I can see all messages from the current inbox, but I need to limit this to only messages which have an attachment. How can I do this?

This is my GoogleController.cs:

[HttpGet]
[Authorize]
public async Task<IActionResult> GetListEmail(string LabelId, string nameLabel)
{
    string UserEmail = User.FindFirst(c => c.Type == ClaimTypes.Email).Value;
    var service = GetService();
    List<My_Message> listMessages = new List<My_Message>();
    List<Message> result = new List<Message>();
    var emailListRequest = service.Users.Messages.List(UserEmail);
    emailListRequest.LabelIds = LabelId;
    emailListRequest.IncludeSpamTrash = false;
    emailListRequest.MaxResults = 1000;
    var emailListResponse = await emailListRequest.ExecuteAsync();

    if (emailListResponse != null && emailListResponse.Messages != null)
    {
        foreach (var email in emailListResponse.Messages)
        {
            var emailInfoRequest = service.Users.Messages.Get(UserEmail, email.Id);
            var emailInfoResponse = await emailInfoRequest.ExecuteAsync();
            if (emailInfoResponse != null)
            {
                My_Message message = new My_Message();
                message.Id = listMessages.Count + 1;
                message.EmailId = email.Id;
                foreach (var mParts in emailInfoResponse.Payload.Headers)
                {
                    if (mParts.Name == "Date")
                        message.Date_Received = mParts.Value;
                    else if (mParts.Name == "From")
                        message.From = mParts.Value;
                    else if (mParts.Name == "Subject")
                        message.Title = mParts.Value;
                }
                listMessages.Add(message);
            }
        }
    }
    ViewBag.Message = nameLabel;
    return View("~/Views/Home/Index.cshtml", listMessages);
}
Questioner
Gerbut_1986
Viewed
145
Raserhin 2020-01-31 17:24

I think a simpler solution would be to query in the Users.messages.list endpoint without the need to create filters.

You can actually use the parameter q to make a query like you would in the GMail searchbox, if not familiar you can look at the whole list of operators.

In fact there is an example to make use of this query parameter in the documentation:

using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;

using System.Collections.Generic;

// ...

public class MyClass {

  // ...

  /// <summary>
  /// List all Messages of the user's mailbox matching the query.
  /// </summary>
  /// <param name="service">Gmail API service instance.</param>
  /// <param name="userId">User's email address. The special value "me"
  /// can be used to indicate the authenticated user.</param>
  /// <param name="query">String used to filter Messages returned.</param>
  public 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; // inform this with the right 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;
  }

  // ...

}

So for your case you just need to add the line

emailListRequest.Q = "has:attachment";

before executing the request, doing like this will not create a whole filter for your account, so maybe it's more convenient for your case.