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

Gmail API - PHP - Sending email using service account

问题: 每当我调用 sendMessage() 方法时,我都会遇到 HTTP 400 错误,该错误指出 "Precondition check failed."。

我不知道我有什么可以考虑的:

  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', 'some@email.com', '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();
  }
}
?>

非常感谢任何帮助!

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

这是支持人员在电子邮件中告诉我的内容:“您必须在代码上模拟用户才能使用服务帐户调用 Gmail API。” 所以“先决条件检查失败。”错误是由于未正确验证造成的。

因此,为了完整起见,我将 运行 介绍让您的代码正常工作所必须经历的过程。请注意,您需要三样东西:G-Suites、访问 Google 开发人员控制台和访问 G-Suites 管理控制台。

开始编码前的要求。

  1. 获取 Google 客户端库(确保 php 在您的系统路径中 > 安装 Composer > 安装库 composer require google/apiclient:^2.0
  2. 启用 Gmail API(Google Developer console > 图书馆 > 搜索 'Gmail API' > 启用(如果已启用,您将看到管理按钮)
  3. 创建服务帐户(Google Developer console > IAM 和管理 > 服务帐户 > 单击 'Create Service Account' > 像往常一样填写第 1 步 > 对于第 2 步,我将我的服务帐户设置为项目所有者。 >第 3 步我跳过了。)
  4. 创建密钥(Google Developer console > IAM 和管理 > 服务帐户 > 单击新创建的服务帐户的 'Actions' 菜单 > 创建密钥 > JSON > 将其存储在您的代码可以访问的位置。)
  5. 设置全域委派(Google Admin > Security > API Permissions > Scroll all the way down to find 'Manage Domain-wide Delegation' > Click 'Add New' > Enter the Client ID found in the json file you just downloaded > Enter in the scopes you need. For sending emails through gmail, look under 'Authorization' here。)
  6. 启用全域委派(Google Developer console > IAM 和管理 > 服务帐户 > 单击新创建的服务帐户 > 单击 'Edit' > 显示全域委派 > 启用 G-Suite 域-广泛代表团)

如果您遵循并完成了这些步骤,就可以继续代码部分了!

代码本身。

<?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 = "your@domain.com";

$sender = $user_to_impersonate;
$to = 'another@domain.com';
$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;
}
 ?>