Search code examples
c#exchangewebservicesgmail-api

How to send base64Url encoded Raw Email message?


I got Gmail RFC 2822 compliant message which contains everything (headers,body,subject etc.). The message is base64url encoded. I am trying to parse this message and send it to Exchange online. So far I have tried Sasa Mime library but this great library doesn't work for me.

string strRaw = System.IO.File.ReadAllText(@"G:\raw.txt");
var mail = Sasa.Net.Mail.Message.Parse(strRaw);

The above code fails with this following exception : Exception Details: System.ArgumentOutOfRangeException: Length cannot be less than zero. Parameter name: length

I request you to tell me which free Mime library I can use to parse Gmail Raw message. Java has a great built-in library called javax.mail.internet (MimeMessage class) which does the job very beautifully. I am using EWS managed Api to work with Exchange online and it's not able to parse Gmail raw message directly.

Edited : removed the encoded message.

best regards,


Solution

  • As you indicated the string is base64url you have to adapt slightly to overcome the difference from orginal base64 as indicated in the wikipedia article.

    The following table shows the differences:

    standard  | 62 | 63 | pad
    -------------------------
    base64    | +  | /  | =
    base64Url | -  | _  | N/A
    

    Using this knowledge it becomes clear how to convert from a base64Url to the base64 standard that is used by Convert.FromBase64String.

    This code shows how that could work:

    var base64Url = "UmVjZWl2 ..... rest of your base64url string ... -";
    
    // replace - and _ with their base64 chars
    var sb64 = new StringBuilder(base64Url)
                  .Replace('-','+')
                  .Replace('_', '/');
    var bin = Convert.FromBase64String(sb64.ToString());    
    
    Encoding.ASCII.GetString(bin).Dump("valid");
    

    Using above code dumped the following result in my console (part of it):

    Received: from removed.googleusercontent.com
    named unknown
    by gmailapi.google.com
    with HTTPREST;
    Sat, 29 Nov 2014 04:55:31 -0800
    MIME-Version: 1.0
    x-no-auto-attachment: 1
    Received: by 10.114.186.6; Mon, 17 Nov 2014 07:11:34 -0800 (PST) Date: Sat, 29 Nov 2014 04:55:31 -0800
    Message-Id: [removed for privacy]
    Subject: Tips for using your new inbox
    From: [removed for privacy]
    To: "Your Team @365innovate" <[removed for privacy] >
    Content-Type: multipart/alternative; boundary=001a11c33c7aee86ee05080f6437

    --001a11c33c7aee86ee05080f6437
    Content-Type: text/plain; charset=UTF-8
    Content-Transfer-Encoding: quoted-printable

    Tips for using your new inbox
    [image: Google]