【问题标题】:Gmail can't decode multiline base64 encoded messageGmail 无法解码多行 base64 编码邮件
【发布时间】:2020-03-13 03:18:46
【问题描述】:

我使用Swift_Message 构造消息并使用Swift_Mime_ContentEncoder_Base64ContentEncoder 对消息进行编码,然后在Google_Service_Gmail_Message 中使用->setRaw() 方法设置编码消息。

我用这个发送邮件已经有一段时间了,它曾经工作得很好。从昨天开始,它停止工作,并且错误消息显示

  "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"
  }

当我删除 CRLF 时它可以工作。有什么想法吗?

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

我的代码

    $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);

【问题讨论】:

  • 你能提供你用来尝试复制问题的代码吗?
  • 这几乎就是代码的编写方式。

标签: gmail gmail-api swiftmailer base64url


【解决方案1】:

我用base64_encode($message->toString());代替了

(new Swift_Mime_ContentEncoder_Base64ContentEncoder)->encodeString($msg->toString());

【讨论】:

  • 这确实解决了问题(我现在正在使用)但不遵循 RFC2822 标准。
  • 好的,如果您找到符合 RFC2822 标准的更好解决方案,请告诉我们
【解决方案2】:

您使用的库方法执行 Base64 编码,并且您需要 documentation 中所述的 Base64URL 编码字符串

【讨论】:

  • 我已经做到了。 rtrim(strtr($data, '+/', '-_'), '=');
  • 您还需要删除行分隔符
  • 但是根据 RFC2822 我不应该在一行中放置超过 76 个字符,并且不能超过 998 个字符!
猜你喜欢
  • 2021-08-04
  • 1970-01-01
  • 2014-09-04
  • 1970-01-01
  • 2016-03-26
  • 1970-01-01
  • 2014-09-08
  • 1970-01-01
  • 2016-11-21
相关资源
最近更新 更多