The Problem: I'm stuck with an HTTP 400 error that states "Precondition check failed." whenever I call the sendMessage() method.
I don't know what it can be considering that I have:
- Enabled Gmail API.
- Created a service account.
- Set up domain-wide delegation (for G-Suites).
- Enabled domain-wide delegation for the service.
As a note, I've successfully run quickstart.php so I know that the google library is installed correctly. Below is my code:
<?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();
}
}
?>
Any help is greatly appreciated!