为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
烙印99 2023-05-12 16:11:36
问题:我一直遇到 HTTP 400 错误,指出“先决条件检查失败”。每当我调用 sendMessage() 方法时。我不知道我有什么可以考虑的:启用 Gmail API。创建了一个服务帐户。设置全域委派(针对 G-Suites)。为服务启用域范围的委派。请注意,我已成功运行 quickstart.php,因此我知道谷歌库已正确安装。下面是我的代码:<?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 usersendMessage($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();  }}?>任何帮助是极大的赞赏!
查看完整描述

1 回答

?
隔江千里

TA贡献1906条经验 获得超10个赞

开始编码之前的要求。

  1. 获取 Google Client Library(确保 php 在您的系统路径中 > Install Composer > Install the library composer require google/apiclient:^2.0

  2. 启用 Gmail API(Google Developer console > Library > Search 'Gmail API' > Enable(如果已启用,您将看到管理按钮)

  3. 创建服务帐户(Google Developer console > IAM & Admin > Service Accounts > 点击“Create Service Account” > 像往常一样填写第 1 步 > 对于第 2 步,我将我的服务帐户设置为项目所有者。 > 第 3 步我跳过了。)

  4. 创建一个密钥(谷歌开发者控制台> IAM 和管理 > 服务账户 > 点击你新创建的服务账户的“操作”菜单 > 创建密钥 > JSON > 将它存储在你的代码可以访问的地方。)

  5. 设置全域委派(Google 管理员> 安全 > API 权限 > 一直向下滚动以找到“管理全域委派” > 点击“添加新” > 输入在您刚刚下载的 json 文件中找到的客户端 ID > 输入在您需要的范围内。要通过 gmail 发送电子邮件,请查看此处的“授权”。)

  6. 启用全域委派(Google Developer console > IAM & Admin > Service Accounts > 单击新创建的服务帐户 > 单击“编辑”> 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 = "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;

}

 ?>


查看完整回答
反对 回复 2023-05-12
  • 1 回答
  • 0 关注
  • 443 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信