Gmail API PHP客户端库 - 如何使用PHP客户端库发送大型附件?

时间:2015-03-16 15:57:43

标签: php gmail email-attachments google-api-php-client gmail-api

我使用Google的PHP客户端库向Gmail的API发送电话。使用这些资源,我可以使用以下代码发送带附件的邮件:

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']);
}

但我不能为我的生活弄清楚如何发送大于几MB的附件。我发现有必要使用multipart上传类型,但我可以根据我目前的情况确切地弄清楚如何实现它,因为上面的代码仍然给我这个错误:

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

This article提供了非常好的广泛信息,但我希望能为谷歌的PHP客户端库提供更多指导。

编辑:根据this page,最大上传大小实际为35 MB。我的php.ini中指定的大小就足够了,请求从谷歌413失败,而不是内部服务器错误。

2 个答案:

答案 0 :(得分:1)

不太熟悉GMail API,但您应该能够使用分块上传来减少每个请求的大小。查看客户端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);
}

答案 1 :(得分:1)

如果您已准备好原始电子邮件,则可以使用此示例(最初取自here):

// size of chunks we are going to send to google    
$chunkSizeBytes = 1 * 1024 * 1024;

// actual raw email message
$mailMessage = 'raw email text with files embedded'

// code to create mime message
$googleClient = new Google_Client();

// code to setup the client
$mailService = new Google_Service_Gmail($googleClient);
$message = new Google_Service_Gmail_Message();

// Call the API with the media upload, defer so it doesn't immediately return.
$googleClient->setDefer(true);

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

// create mediafile upload
$media = new Google_Http_MediaFileUpload(
    $googleClient,
    $request,
    'message/rfc822',
    $mailMessage,
    true,
    $chunkSizeBytes
);
$media->setFileSize(strlen($mailMessage));

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

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

// Get sent email message id
$googleMessageId = $status->getId();