Search code examples
gmail-api

Message.Payload is always null for all messages. How do I get this data?


It is returning the correct number of message, but the only fields that are populated are Id and ThreadId. Everything else is null

        var service = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });

        ListMessagesResponse response = service.Users.Messages.List(emailAddress).Execute();

        IList<Google.Apis.Gmail.v1.Data.Message> messages = response.Messages;

        Console.WriteLine("Messages:");
        if (messages != null && messages.Count > 0)
        {
            foreach (var message in messages)
            {
                Console.WriteLine("{0}", message.Payload.Body);
                Console.WriteLine();
            }
        }
        else
        {
            Console.WriteLine("No Messages found.");
        }

Solution

  • Messages.List() only returns message and thread ids. To retrieve message contents, you need to invoke Get() for each message you are interested in. Updated version of your foreach loop example:

    foreach (var message in messages)
    {
        Message m = service.Users.Messages.Get("me", message.Id).Execute();
        // m.Payload is populated now.
        foreach (var part in m.Payload.Parts)
        {
            byte[] data = Convert.FromBase64String(part.Body.Data);
            string decodedString = Encoding.UTF8.GetString(data);
            Console.WriteLine(decodedString);
        }
    }
    

    Note: You may need to run a string replace on the part.Body.Data string. See this post for instructions.