10

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

Tobbe
  • 1,825
  • 3
  • 21
  • 37
Turgut Kanceltik
  • 639
  • 1
  • 8
  • 18
  • 1
    What exactly are you printing? Your method seems to correctly return a Message object, but without knowing what you are doing afterwards, we can't help you. – Lars Kristensen Oct 08 '15 at 07:39

2 Answers2

7

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);
}
Tobbe
  • 1,825
  • 3
  • 21
  • 37
0

Based on this SO answer for decoding a base64 url encoded string, this is how I used to fetch the most likely message part that contains the text or html that the user sees:

string? GetMessageBodyText(Message message) {
    var part = message.Payload;

    while (part is not null) {
        var mimeType = part.MimeType;

        if (mimeType is "text/plain" or "text/html") {
            return DecodeBase64UrlString(part.Body.Data);
        }

        part = part.Parts?.FirstOrDefault();
    }

    return null;
}

string DecodeBase64UrlString(string encoded) {
    var dec = encoded.Replace("-", "+").Replace("_", "/");
    var data = Convert.FromBase64String(dec);
    var decodedString = Encoding.UTF8.GetString(data);
    return decodedString;
}
Aviad P.
  • 32,036
  • 14
  • 103
  • 124