Search code examples
phpgmailemail-attachmentsgoogle-api-php-clientgmail-api

Gmail API PHP Client Library - How do you send large attachments using the PHP client library?


I'm using Google's PHP client library to send calls to Gmail's API. Using those resources, I can send messages with attachments using code like this:

public function send_message(Google_Service_Gmail $gmail, $raw_message)
{
    Log::info('Gmail API request \'users_messages->send\'');
    $postBody = new Google_Service_Gmail_Message();
    $postBody->setRaw(Str::base64_encode_url($raw_message));
    return $gmail->users_messages->send('me', $postBody, ['uploadType' => 'multipart']);
}

But I can't for the life of me figure out how send attachments larger than a few MB. I've found that it is necessary to use multipart uploadtype, but I can figure out exactly how to implement that based on what I currently have, as the code above still gives me this error:

Error calling POST https://www.googleapis.com/gmail/v1/users/me/messages/send?uploadType=multipart
Error 413: Request Entity Too Large

This article has really good broad strokes information, but I'm hoping for a little bit more guidance specific to Google's PHP client library.

EDIT: According to this page, the maximum upload size is actually 35 MB. The size specified in my php.ini is sufficient for this, and the requests fails as a 413 from google, not an internal server error.


Solution

  • Not too familiar with the GMail API, but you should be able to use chunked uploads to reduce the size of each individual request. Take a look at the file upload sample in the client Github: https://github.com/google/google-api-php-client/blob/master/examples/fileupload.php#L73

    $media = new Google_Http_MediaFileUpload(
      $client,
      $request,
      'text/plain',
      null,
      true,
      $chunkSizeBytes
    );
    
    $media->setFileSize(filesize(TESTFILE));
    $status = false;
    $handle = fopen(TESTFILE, "rb");
    while (!$status && !feof($handle)) {
      $chunk = fread($handle, $chunkSizeBytes);
      $status = $media->nextChunk($chunk);
    }