Invalid value for ByteString error when calling gmail send API with base64 encoded < or>

后端 未结 5 1353
南笙
南笙 2021-01-03 22:07

Really stuck on this one and pulling my hair out trying to figure out what to do, searched everywhere and tried everything but still stuck. Any help is much appreciated.

相关标签:
5条回答
  • 2021-01-03 22:29

    If you are using PHP try this (otherwise try converting it to whatever language you are using)

    Call the below function on your mime message before setting it to the raw property.

    private function base64url_encode($mime) {
        return rtrim(strtr(base64_encode($mime), '+/', '-_'), '=');
    }
    
    0 讨论(0)
  • 2021-01-03 22:31

    The Google API decodes with urlsafe_b64decode. Try to use urlsafe_b64encode (encode strings using a URL-safe alphabet, which uses - instead of + and _ instead of / in the standard Base64 alphabet.)

    In your example I see one + which means you used standard Base64.

    0 讨论(0)
  • 2021-01-03 22:41

    After you encode your message contents via base64Encode, like here (assuming google script):

    var draftBody =  Utilities.base64Encode(message_content_string);
    

    you have to convert all '/' and '+' characters that are not 'web-safe' and will produce the "Invalid value for ByteString" error. You can do it this way:

    draftBody = draftBody.replace(/\//g,'_').replace(/\+/g,'-');
    

    Then you submit it as a raw data. Apparently there is no distortion of message contents here.

    0 讨论(0)
  • 2021-01-03 22:44

    From Google's gmail rest api (sending messages):

    "The entire email message in an RFC 2822 formatted and base64url encoded string. Returned in messages.get and drafts.get responses when the format=RAW parameter is supplied."

    base64url encoding is not the same as base64 encoding.

    in python, the base64 library offers b64encode() and urlsafe_b64encode(). If you don't use urlsafe_b64encode(), you will get that error, not all the time so it may pass a simple unit test, but it will fail soon enough.

    0 讨论(0)
  • 2021-01-03 22:45

    In Google Apps Script following fixes the issue

    var draftBody = Utilities.base64EncodeWebSafe(raw);
    

    Don't use var draftBody = Utilities.base64Encode(raw);

    0 讨论(0)
提交回复
热议问题