Search code examples
c#gmail-api

How can I read the whole message using Gmail API


I need all the text in the body for incoming email.

I tried:

var mesage = GetMessage(service, "me", 1);
Console.WriteLine(mesage.Snippet);

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

But I am getting just snippet as shown in the screenshot.

Incoming mail to me: enter image description here Result:

enter image description here


Solution

  • Looking at the documentation, Message.Snippet only returns a short part of the message text. You should instead use Message.Raw, or more appropriately, Message.Payload.Body?

    var message = GetMessage(service, "me", 1);
    Console.WriteLine(message.Raw);
    Console.WriteLine(message.Payload.Body.Data);
    

    You should try both out and see what works best for what you're trying to do. To get message.Raw you need to pass a parameter, as stated in the docs:

    Returned in messages.get and drafts.get responses when the format=RAW parameter is supplied.

    If none of those things work, you could try iterating over the parts of the message to find your data:

    foreach (var part in message.Payload.Parts)
    {
        byte[] data = Convert.FromBase64String(part.Body.Data);
        string decodedString = Encoding.UTF8.GetString(data);
        Console.WriteLine(decodedString);
    }