如何使用Gmail API将草稿电子邮件同步到Gmail中已有附件超过20MB的现有线程

时间:2018-08-02 11:09:55

标签: gmail-api

我正在使用MediaFileUpload类创建带有大小超过20MB的附件的电子邮件。我已经阅读了Gmail API上传附件文档。但是下面的异常一直出现。请帮助我解决这个问题。

    $service = $this->getClientService();
    $client = $this->getClientConnection();

    $draft = new Google_Service_Gmail_Draft();
    $draft->setMessage($message);

    // mime message format
    $rawMessage = $this->getOriginalRawMessage();
    $client->setDefer(TRUE);
    try {
        $request = $service->users_drafts->create($userId, $draft,['uploadType' => 'multipart']);
        $media = new Google_Http_MediaFileUpload($client, $request, 'multipart/related',$rawMessage, false, self::MESSAGE_UPLOAD_CHUNK_SIZE);
        $media->setFileSize(strlen($rawMessage));
        // Upload the various chunks. $draftResponse will be false until the process is complete.
        $mediaResponse = false;
        while (!$mediaResponse) {
            $mediaResponse = $media->nextChunk();
        }
        $client->setDefer(false);

      return $mediaResponse;

获取异常

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "badContent",
    "message": "Media type 'application/json; charset=UTF-8' is not supported. Valid media types: [message/rfc822]"
   }
  ],
  "code": 400,
  "message": "Media type 'application/json; charset=UTF-8' is not supported. Valid media types: [message/rfc822]"
 }
}

1 个答案:

答案 0 :(得分:0)

   $service = $this->getClientService();
    $googleClient = $this->getClientConnection();

    $draft = new Google_Service_Gmail_Draft();
    $draft->setMessage($message);
    try {
        // Original raw message (i.e rfc822 format),
        // Note: Content should not be in encoded format
        $mailMessage = $this->getOriginalMessage();

        // This flag is not to call the request, immediately, instead it queues, when flag is true
        $googleClient->setDefer(true);

        $request = $service->users_drafts->create('me', $draft);

        // create mediafile upload
        $media = new Google_Http_MediaFileUpload($googleClient, $request, 'message/rfc822', $mailMessage, true,
                self::MESSAGE_UPLOAD_CHUNK_SIZE);

        // Length of mail message(rfc822)
        $media->setFileSize(strlen($mailMessage)); 

        // Upload the various chunks. $status will be false until the process is complete.
        $draftObject = false;
        while (!$draftObject) {
            $draftObject = $media->nextChunk();
        }

        // Reset to the client to execute requests immediately in the future.
        $googleClient->setDefer(false);
        return $draftObject;