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

标签 php gmail-api google-workspace

问题:我遇到了一个 HTTP 400 错误,指出“前提条件检查失败”。每当我调用 sendMessage() 方法时。

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

  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 & Admin > 服务帐户 > 点击“创建服务帐户” > 照常填写第 1 步 > 第 2 步,我将我的服务帐户设置为项目所有者。 > 第 3 步我跳过了.)
  4. 创建一个 key (Google Developer console > IAM 和管理员 > 服务帐户 > 点击新创建的服务帐户的“操作”菜单 > 创建 key > JSON > 将其存储在您的代码可以访问的位置。)
  5. 设置域范围委派(Google Admin > 安全 > API 权限 > 一直向下滚动以找到“管理域范围委派”> 单击“添加新”> 输入您在 json 文件中找到的客户端 ID刚刚下载 > 输入您需要的范围。通过 gmail 发送电子邮件,look under 'Authorization' here。)
  6. 启用域范围委派(Google Developer console > IAM 和管理员 > 服务帐户 > 单击新创建的服务帐户 > 单击“编辑”> 显示域范围委派 > 启用 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;
}
 ?>

关于php - Gmail API - PHP - 使用服务帐户发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62312730/

相关文章:

php - Amazon SNS 端点在 php 中被禁用但是当我记录响应时我得到的端点状态为已启用

google-apps-script - Google 应用程序脚本部署为 Web 应用程序卡在获取数据

google-apps-script - 如何在 Google 电子表格之间共享我的应用脚本?

google-apps-script - 以 "unlisted"模式在 GSuite 市场上发布附加组件

php - 在 PHP 中使用 mysqli 连接到 MySQL 时出现问题

javascript - AJAX请求成功但返回空数据

gmail - 如何从 gmail api 获取 "All Mail"标签?

python - Gmail 邮件正文的编码是什么?如何解码?

php - 通过引用使用 __get()

android - 在未经用户同意的情况下处理 Android 中过期的访问 token