Gmail API - PHP - 使用服务帐户发送电子邮件。

问题描述 投票:0回答:1

问题。 每当我调用sendMessage()方法时,我都会被一个HTTP 400错误卡住 "Precondition检查失败"。

我不知道这可能是什么原因,考虑到我已经。

  1. 启用了Gmail API
  2. 创建了一个服务账户。
  3. 设置了全域授权(针对G-Suites)。
  4. 启用了服务的全域授权。

作为一个说明,我已经成功运行了 quickstart.php,所以我知道google库是正确安装的。下面是我的代码。

<?php
 require_once('../../vendor/autoload.php');

$client = new Google_Client();
$credentials_file = '../../vendor/google/auth/credentials.json';

$client->setAuthConfig($credentials_file);
$client->setApplicationName("no-reply mailing");
$client->setScopes(['https://www.googleapis.com/auth/gmail.send']);
$service = new Google_Service_Gmail($client);
$message = createMessage('me', '[email protected]', 'This is but a test', 'Please work...');

// Email a user
sendMessage($service, 'me', $message);

/**
* @param $sender string sender email address
* @param $to string recipient email address
* @param $subject string email subject
* @param $messageText string email text
* @return Google_Service_Gmail_Message
*/
function createMessage($sender, $to, $subject, $messageText) {
 $message = new Google_Service_Gmail_Message();

 $rawMessageString = "From: <{$sender}>\r\n";
 $rawMessageString .= "To: <{$to}>\r\n";
 $rawMessageString .= 'Subject: =?utf-8?B?' . base64_encode($subject) . "?=\r\n";
 $rawMessageString .= "MIME-Version: 1.0\r\n";
 $rawMessageString .= "Content-Type: text/html; charset=utf-8\r\n";
 $rawMessageString .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
 $rawMessageString .= "{$messageText}\r\n";

 $rawMessage = strtr(base64_encode($rawMessageString), array('+' => '-', '/' => '_'));
 $message->setRaw($rawMessage);
 return $message;
}

function sendMessage($service, $userId, $message) {
  try {
    $message = $service->users_messages->send($userId, $message);
    print 'Message with ID: ' . $message->getId() . ' sent.';
    return $message;
  } catch (Exception $e) {
    print 'An error occurred: ' . $e->getMessage();
  }
}
?>

任何帮助都是非常感激的!

php gmail-api gsuite
1个回答
1
投票

我联系了Google的支持,他们已经解决了我的问题!

以下是支持部门在邮件中告诉我的内容。"你必须在代码中冒充用户 才能用服务账户调用Gmail API" 所以 "预设条件检查失败。"的错误是由于没有正确认证造成的。

所以为了完整起见,我将运行你必须经历的过程,以使你的代码工作。注意,你将需要三样东西。G -Suites,访问谷歌开发者控制台 和访问G -Suites管理控制台。

在你开始编码之前的要求。

  1. 获取谷歌客户端库(确保php在你的系统路径中>Install 作曲家 > 安装库 composer require google/apiclient:^2.0)
  2. 启用Gmail API (谷歌开发者控制台 > Library > Search 'Gmail API' > Enable (如果已经启用,你会看到管理按钮)
  3. 创建服务账户 (谷歌开发者控制台 > IAM & Admin > Service Accounts > Click 'Create Service Account' > Fill in Step 1 as usual > For Step 2, I set my service account as project owner. > Step 3 I skipped.)
  4. 创建一个密钥(谷歌开发者控制台 > IAM & Admin > Service Accounts > 点击'Actions'菜单上新创建的服务账户 > Create Key > JSON > 将其存储在你的代码可以访问的地方)。
  5. 设置全域授权(谷歌管理 > Security > API Permissions > 向下滚动找到'Manage Domain-wide Delegation' > 点击'Add New' > 输入在你刚刚下载的json文件中找到的客户端ID > 输入你需要的范围。对于通过gmail发送邮件。在 "授权 "下查找.)
  6. 启用全域授权 (谷歌开发者控制台 > IAM & Admin > Service Accounts > Click on newly created service account > Click 'Edit' > Show Domain-wide Delegation > Enable G-Suite Domain-wide Delegation)

如果你已经遵循并完成了这些步骤,你就可以继续进入代码部分了!

代码本身。

<?php
// Library obtained from https://developers.google.com/gmail/api/quickstart/php
require_once('../../vendor/autoload.php');

// Some user within your G-Suites domain
$user_to_impersonate = "[email protected]";

$sender = $user_to_impersonate;
$to = '[email protected]';
$subject = 'The subject of an email.';
$messageText = 'Finally this works!';

// The path to your service account credentials goes here.
putenv("GOOGLE_APPLICATION_CREDENTIALS=credentials.json");
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setSubject($sender);
$client->setApplicationName("Quickstart");
$client->setScopes(["https://mail.google.com/",
                    "https://www.googleapis.com/auth/gmail.compose",
                    "https://www.googleapis.com/auth/gmail.modify",
                    "https://www.googleapis.com/auth/gmail.send"]);
$service = new Google_Service_Gmail($client);

// Main Process
try {
  $msg = createMessage($sender, $to, $subject, $messageText);
  sendMessage($service, $sender, $msg);
} catch (Exception $e) {
  print "An error occurred: " . $e->getMessage();
}

function sendMessage($service, $sender, $msg) {
  $service->users_messages->send($sender, $msg);
}

function createMessage($sender, $to, $subject, $messageText) {
  $rawMsgStr = "From: <{$sender}>\r\n";
  $rawMsgStr .= "To: <{$to}>\r\n";
  $rawMsgStr .= 'Subject: =?utf-8?B?' . base64_encode($subject) . "?=\r\n";
  $rawMsgStr .= "MIME-Version: 1.0\r\n";
  $rawMsgStr .= "Content-Type: text/html; charset=utf-8\r\n";
  $rawMsgStr .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
  $rawMsgStr .= "{$messageText}\r\n";

  // The message needs to be encoded in Base64URL
  $mime = rtrim(strtr(base64_encode($rawMsgStr), '+/', '-_'), '=');
  $msg = new Google_Service_Gmail_Message();
  $msg->setRaw($mime);
  return $msg;
}
 ?>
© www.soinside.com 2019 - 2024. All rights reserved.