Send large attachment with Gmail API

廉价感情. 提交于 2019-12-11 08:45:03

问题


According to Gmail API to send an email with large attachments bigger then 5MB you need to use the instructions here: https://developers.google.com/gmail/api/guides/uploads

The API is a not very clear about the details and I tried to use the explanation I found here: Gmail API PHP Client Library - How do you send large attachments using the PHP client library?

I get "Entity too large" error message every time.

Someone can succeded to send an attachment bigger than 5MB with Gmail API, and help me understand what I'm doing wrong?

My composer file:

{
    "require": {
        "google/apiclient": "^2.0",
        "pear/mail_mime": "^1.10"
    }
}

My code after reading everything is this:

<?php
set_time_limit(100);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/vendor/autoload.php';
require_once 'client.php';

$googleClient = getClient();

$mailService = new Google_Service_Gmail($googleClient);
$message = new Google_Service_Gmail_Message;

$file = __DIR__ . '/pexels-photo.jpg';

$mime = new Mail_mime;
$mime->addTo('mymail@domain.com');
$mime->setTXTBody('');
$mime->setSubject('test');

$mailMessage = base64_encode($mime->getMessage());
$message->setRaw($mailMessage);

$request = $mailService->users_messages->send(
    'me',
    $message,
    array( 'uploadType' => 'resumable' )
);

$googleClient->setDefer(true);

$media = new Google_Http_MediaFileUpload(
    $googleClient,
    $request,
    'message/rfc822',
    $mailMessage,
    $resumable = true,
    $chunkSizeBytes = 1 * 1024 * 1024
);

$media->setFileSize(filesize($file));

$status = false;
$handle = fopen($file, 'rb');
while (! $status && ! feof($handle)) {
    $chunk = fread($handle, $chunkSizeBytes);
    $status = $media->nextChunk($chunk);
}

fclose($handle);

$googleClient->setDefer(false);

回答1:


@MP In my case, the problem is that I needed to set the unencoded message size, not the actual file. like this:

$media->setFileSize(strlen($message));


来源:https://stackoverflow.com/questions/49362380/send-large-attachment-with-gmail-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!