1

I'm using Swift_Message to construct the message and Swift_Mime_ContentEncoder_Base64ContentEncoder to encode the message,then in Google_Service_Gmail_Message I'm setting the encoded mesage with ->setRaw() method.

I've been sending mail with this for quite some time and it used to work fine. Since yesterday it stopped working and the error message says

  "error": {
    "code": 400,
    "message": "Invalid value at 'message.raw' (TYPE_BYTES), Base64 decoding failed for \"[base64 encoded message with CRLF after every 76th character]\"",
    "errors": [
      {
        "message": "Invalid value at 'message.raw' (TYPE_BYTES), Base64 decoding failed for \"[base64 encoded message with CRLF after every 76th character]\"",
        "reason": "invalid"
      }
    ],
    "status": "INVALID_ARGUMENT"
  }

It works when I remove the CRLF. Any thoughts?

Ref: https://www.rfc-editor.org/rfc/rfc2822#section-2.1.1

My code

    $msg = new Swift_Message();
    $msg->setCharset('UTF-8')
        ->addTo(/*recipient*/)
        ->setSubject(/*sbject*/)
        ->addPart(/*text content*/, "text/plain")
        ->addPart(/*html content*/, "text/html");
        
    $base64 = (new Swift_Mime_ContentEncoder_Base64ContentEncoder)->encodeString($msg->toString());
    $base64_msg = rtrim(strtr($base64, '+/', '-_'), '=');

    $mailer  = $this->_getGmailService();// new Google_Service_Gmail(new Google_Client())
    $message = new Google_Service_Gmail_Message();
    $message->setRaw($base64_msg);
    $message->setThreadId($threadId);

    $mailer->users_messages->send('me', $message);
Community
  • 1
  • 1
Rocky
  • 519
  • 6
  • 18

2 Answers2

2

I used base64_encode($message->toString()); instead of

(new Swift_Mime_ContentEncoder_Base64ContentEncoder)->encodeString($msg->toString());
N Nem
  • 743
  • 8
  • 14
0

The library method you're using does a Base64 encoding and you need a Base64URL encoded string as stated in the documentation

Andres Duarte
  • 3,166
  • 1
  • 7
  • 14