1

I'm trying to decode the message.Raw field like this:

byte[] mailContent = Convert.FromBase64String(message.Raw);

but I'm getting a System.FormatException.

What am I missing here? Is necessary to do some aditional step? Thanks.

**Edit:** The message.Raw content is too big to post it here so I've uploaded an example.

Daniel Marín
  • 1,369
  • 14
  • 36
  • Are you sure the `message.Raw` is in `Base64` form? Add your string content to the question. – Yuval Itzchakov Aug 01 '14 at 10:46
  • Ok, I have to create a new gmail account to do that, because the message.Raw is directly returned by the Gmail API so it contains emails and other sensible info. – Daniel Marín Aug 01 '14 at 10:50
  • Take a look at the original post that I've just edited. – Daniel Marín Aug 01 '14 at 11:23
  • Solution found here: http://stackoverflow.com/questions/24464866/having-trouble-reading-the-text-html-message-part?rq=1 – Daniel Marín Aug 01 '14 at 12:00
  • This question is duplicated, but it was very difficult to me to find the original question (bad tags and title). I'm not going to delete this, because it will help people to find the answer. – Daniel Marín Oct 14 '14 at 09:55

2 Answers2

3

The message.Raw field is not only Base64 encoded, but also URL-safe encoded.

Have a look at this question: Code for decoding/encoding a modified base64 URL

Original code taken from link above:

///<summary>
/// Base 64 Encoding with URL and Filename Safe Alphabet using UTF-8 character set.
///</summary>
///<param name="str">The origianl string</param>
///<returns>The Base64 encoded string</returns>
public static string Base64ForUrlEncode(string str)
{
    byte[] encbuff = Encoding.UTF8.GetBytes(str);
    return HttpServerUtility.UrlTokenEncode(encbuff);
}
///<summary>
/// Decode Base64 encoded string with URL and Filename Safe Alphabet using UTF-8.
///</summary>
///<param name="str">Base64 code</param>
///<returns>The decoded string.</returns>
public static string Base64ForUrlDecode(string str)
{
    byte[] decbuff = HttpServerUtility.UrlTokenDecode(str);
    return Encoding.UTF8.GetString(decbuff);
}
Community
  • 1
  • 1
EFrank
  • 1,880
  • 1
  • 25
  • 33
  • Yeah, I had already read that, but `HttpServerUtility.UrlTokenDecode(message.Raw);` returns `null` – Daniel Marín Aug 01 '14 at 11:15
  • @Daniel Marin: This is strange, because I could not see anything about returning null in the documentation of UrlTokenDecode. – EFrank Aug 01 '14 at 11:52
  • 1
    It is because the `message.Raw` is not in the correct format. I found the solution in this post anyway: http://stackoverflow.com/questions/24464866/having-trouble-reading-the-text-html-message-part?rq=1 – Daniel Marín Aug 01 '14 at 11:57
1

It is because the message.Raw is not in the correct format. I found the solution in this post.

Community
  • 1
  • 1
Daniel Marín
  • 1,369
  • 14
  • 36