问题:我一直遇到 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 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();
}
}
?>
任何帮助是极大的赞赏!
隔江千里