Gmail API:尝试发送电子邮件时出现 400 错误请求(PHP 代码)
Gmail API: 400 bad request when trying to send an email (PHP code)
我希望下面的代码能够发送电子邮件,但我只收到了:
An error occurred: Error calling POST
https://www.googleapis.com/gmail/v1/users/me/messages/send: (400) Bad
Request
我使用底部的 Google 开发人员控制台 here 获得 200 OK
。有帮助吗?
$client_id = '599901532082-js1r50n20q6n5mir9fo1g81qkj9kfn3j.apps.googleusercontent.com';
$service_account_name = '599901532082-js1r50n20q6n5mir9fo1g81qkj9kfn3j@developer.gserviceaccount.com';
$key_file_location = '/tmp/APIProject-cb6558ba6435.p12';
$client = new \Google_Client();
$client->setApplicationName("Client_Library_Examples");
$service = new \Google_Service_Gmail($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new \Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.compose'),
$key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
//check if you want the validity of this string at: http://www.komeil.com/toolbox/base64decoder
//it is web safe base64 encoded email
$mime = "RnJvbTogSm9obiBEb2UgPHRpcmVuZ2FyZmlvQGdtYWlsLmVzPiANClRvOiBNYXJ5IFNtaXRoIDx0aXJlbmdhcmZpb0BnbWFpbC5jb20-IA0KU3ViamVjdDogU2F5aW5nIEhlbGxvIA0KRGF0ZTogRnJpLCAyMSBOb3YgMTk5NyAwOTo1NTowNiAtMDYwMCANCk1lc3NhZ2UtSUQ6IDwxMjM0QGxvY2FsLm1hY2hpbmUuZXhhbXBsZT4NCg0KVGhpcyBpcyBhIG1lc3NhZ2UganVzdCB0byBzYXkgaGVsbG8uIFNvLCAiSGVsbG8iLg==";
$service = new \Google_Service_Gmail($client);
$msg = new \Google_Service_Gmail_Message();
$msg->setRaw($mime);
try {
$results = $service->users_messages->send("me", $msg);
print 'Message with ID: ' . $message->getId() . ' sent.';
return $message;
} catch (\Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
编辑:
这是请求对象。它还包括响应数据:
object(Google_Http_Request)[508]
private 'batchHeaders' =>
array (size=3)
'Content-Type' => string 'application/http' (length=16)
'Content-Transfer-Encoding' => string 'binary' (length=6)
'MIME-Version' => string '1.0' (length=3)
protected 'queryParams' =>
array (size=0)
empty
protected 'requestMethod' => string 'POST' (length=4)
protected 'requestHeaders' =>
array (size=3)
'content-type' => string 'application/json; charset=UTF-8' (length=31)
'authorization' => string 'Bearer ya29.8gEUMiBLfxS8OLdSmpiQ-EcumeATo2qFAfPtPqwTw9fQ2zVrfZaA1X5OLoBmQccrXr8V8g' (length=82)
'accept-encoding' => string 'gzip' (length=4)
protected 'baseComponent' => string 'https://www.googleapis.com' (length=26)
protected 'path' => string '/gmail/v1/users/me/messages/send' (length=32)
protected 'postBody' => string '{"raw":"RnJvbTogSm9obiBEb2UgPHRpcmVuZ2FyZmlvQGdtYWlsLmVzPg0KVG86IE1hcnkgU21pdGggPHRpcmVuZ2FyZmlvQGdtYWlsLmNvbT4NClN1YmplY3Q6IFNheWluZyBIZWxsbw0KDQpUaGlzIGlzIGEgbWVzc2FnZSBqdXN0IHRvIHNheSBoZWxsby4gU28sICdIZWxsbycu"}' (length=214)
protected 'userAgent' => string 'Client_Library_Examples google-api-php-client/1.0.6-beta (gzip)' (length=63)
protected 'canGzip' => boolean true
protected 'responseHttpCode' => null
protected 'responseHeaders' => null
protected 'responseBody' => null
protected 'expectedClass' => string 'Google_Service_Gmail_Message' (length=28)
public 'accessKey' => null
object(Google_Http_Request)[508]
private 'batchHeaders' =>
array (size=3)
'Content-Type' => string 'application/http' (length=16)
'Content-Transfer-Encoding' => string 'binary' (length=6)
'MIME-Version' => string '1.0' (length=3)
protected 'queryParams' =>
array (size=0)
empty
protected 'requestMethod' => string 'POST' (length=4)
protected 'requestHeaders' =>
array (size=4)
'content-type' => string 'application/json; charset=UTF-8' (length=31)
'authorization' => string 'Bearer ya29.8gEUM***fxS8OLdSmpiQ-EcumeATo2qFAfPtPqwTw9fQ2zVrfZaA1X5OLoBmQccrXr8V8g' (length=82)
'accept-encoding' => string 'gzip' (length=4)
'content-length' => int 214
protected 'baseComponent' => string 'https://www.googleapis.com' (length=26)
protected 'path' => string '/gmail/v1/users/me/messages/send' (length=32)
protected 'postBody' => string '{"raw":"RnJvbTogSm9obiBEb2UgPHRpcmVuZ2FyZmlvQGdtYWlsLmVzPg0KVG86IE1hcnkgU21pdGggPHRpcmVuZ2FyZmlvQGdtYWlsLmNvbT4NClN1YmplY3Q6IFNheWluZyBIZWxsbw0KDQpUaGlzIGlzIGEgbWVzc2FnZSBqdXN0IHRvIHNheSBoZWxsby4gU28sICdIZWxsbycu"}' (length=214)
protected 'userAgent' => string 'Client_Library_Examples google-api-php-client/1.0.6-beta (gzip)' (length=63)
protected 'canGzip' => boolean true
protected 'responseHttpCode' => int 400
protected 'responseHeaders' =>
array (size=13)
'vary' => string 'Origin
X-Origin' (length=15)
'content-type' => string 'application/json; charset=UTF-8' (length=31)
'content-encoding' => string 'gzip' (length=4)
'date' => string 'Fri, 18 Sep 2015 08:34:25 GMT' (length=29)
'expires' => string 'Fri, 18 Sep 2015 08:34:25 GMT' (length=29)
'cache-control' => string 'private, max-age=0' (length=18)
'x-content-type-options' => string 'nosniff' (length=7)
'x-frame-options' => string 'SAMEORIGIN' (length=10)
'x-xss-protection' => string '1; mode=block' (length=13)
'server' => string 'GSE' (length=3)
'alternate-protocol' => string '443:quic,p=1' (length=12)
'alt-svc' => string 'quic=":443"; p="1"; ma=604800' (length=29)
'transfer-encoding' => string 'chunked' (length=7)
protected 'responseBody' => string '{
"error": {
"errors": [
{
"domain": "global",
"reason": "failedPrecondition",
"message": "Bad Request"
}
],
"code": 400,
"message": "Bad Request"
}
}
' (length=179)
protected 'expectedClass' => string 'Google_Service_Gmail_Message' (length=28)
public 'accessKey' => null
在字符串中使用 URL Endocde 和 url。
这个错误是space在url。
我认为您忘记了将 $client_id
分配给您的 $client
变量。
$client = new Google_Client();
$client->setApplicationName('Gmail API test');
$client->setDeveloperKey('<YOUR_API_KEY>');
$client->setClientSecret('<YOUR_CLIENT_SECRET>');
$client->SetClientId('599901532082-js1r50n20q6n5mir9fo1g81qkj9kfn3j.apps.googleusercontent.com');
$client->setScopes(array('https://www.googleapis.com/auth/gmail.send'));
$client->setAccessToken('{"access_token":"<YOUR_ACCESS_TOKEN>",
"token_type":"Bearer","expires_in":3600,
"refresh_token":"<YOUR_REFRESH_TOKEN>","created":12344556}');
$service = new Google_Service_Gmail($client);
$raw = "RnJvbTogSm9obiBEb2UgPHRpcmVuZ2FyZmlvQGdtYWlsLmVzPiANClRvOiBNYXJ5IFNtaXRoIDx0aXJlbmdhcmZpb0BnbWFpbC5jb20-IA0KU3ViamVjdDogU2F5aW5nIEhlbGxvIA0KRGF0ZTogRnJpLCAyMSBOb3YgMTk5NyAwOTo1NTowNiAtMDYwMCANCk1lc3NhZ2UtSUQ6IDwxMjM0QGxvY2FsLm1hY2hpbmUuZXhhbXBsZT4NCg0KVGhpcyBpcyBhIG1lc3NhZ2UganVzdCB0byBzYXkgaGVsbG8uIFNvLCAiSGVsbG8iLg==";
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($raw);
$results = $service->users_messages->send("me", $msg);
print 'Message with ID: ' . $message->getId() . ' sent.';
终于可以使用您的代码发送邮件了:
我认为您对 GMail API 有一点误解。
要使用它,您必须向 API 进行身份验证。为此,有两种方法:
- 使用 OAuth - 服务器将用户重定向到 google 的服务器,他们可以在其中登录、向您的应用授予权限,并将令牌传回给您
- 服务帐户。这些有点复杂:
- 首先,您必须设置一个应用程序(完成)
- 其次,您必须设置一个服务帐户。这就是您的应用向 google 进行身份验证的方式。你已经做到了,你得到的证书包含用于验证的私钥
- 第三,用户需要授予您的应用程序访问权限才能代表他们行事。这是你还没有完成的点。
那么您目前正在尝试从服务帐户发送邮件,但这不是 GMail 帐户。
Developer Console使用的是OAuth方式,试试这个没有问题。
另请注意:对于常规 GMail 帐户,您可以不使用'Service Accounts'。您将不得不使用 OAuth。
要使用服务帐户,您需要成为 Google Apps 客户。
我不会在这里转换 OAuth 授权,因为它完全不同,并且那里有很多 示例。
要授予您的服务帐户权限以代表您的 GMails/Google Apps 帐户发送邮件,请按照
this document。对于 One or More API Scopes
,您必须输入
https://mail.google.com/,https://www.googleapis.com/auth/gmail.modify,https://www.googleapis.com/auth/gmail.compose,https://www.googleapis.com/auth/gmail.send
.
设置完成后,就可以发送邮件了,修改代码如下:
$results = $service->users_messages->send("me", $msg);
不起作用,因为 'me' 指的是无法发送邮件的服务帐户(见上文)。
将 me
替换为应发送邮件的帐户的用户 ID(邮件地址)。:
$results = $service->users_messages->send("senders_mail@domain.com", $msg);
然后,您需要添加
$cred->sub = 'senders_mail@domain.com';
低于
$cred = new \Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.compose'),
$key
);
另请注意 $message
在 try...catch
-Block 中应该是 $msg
。
在下面,您会找到适合我的完整、有效的代码:
<?php
require_once realpath(dirname(__FILE__) . '/../src/Google/autoload.php');
$client_id = '*censored*.apps.googleusercontent.com';
$service_account_name = '*censored*@developer.gserviceaccount.com';
$key_file_location = '/tmp/apiKey.p12';
$userid_from='*censored*';
$client = new \Google_Client();
$client->setApplicationName("Client_Library_Examples");
//hmmm, really don't know whether these lines are necessary
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new \Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.compose', 'https://www.googleapis.com/auth/gmail.modify','https://www.googleapis.com/auth/gmail.readonly'),
$key
);
$cred->sub=$userid_from; //<-- Important!
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
//check if you want the validity of this string at: http://www.komeil.com/toolbox/base64decoder
//it is web safe base64 encoded email
$mime = "*censored*, same content as you posted, but another recipient ;-)";
$service = new \Google_Service_Gmail($client);
$msg = new \Google_Service_Gmail_Message();
$msg->setRaw($mime);
try {
$results = $service->users_messages->send($userid_from, $msg);
print 'Message with ID: ' . $results->id . ' sent.';
} catch (\Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
如果还有什么问题,欢迎随时提问!
这是一个完整的工作示例,只需确保更改所有适当的信息并使用PHPMailer 来格式化有效的邮件。
<?php
// this the link to gmail-api-client or whatever you have...
require 'vendor/autoload.php';
// download PHPMailer
// https://github.com/PHPMailer/PHPMailer and uncomment the line below.
// require 'PHPMailer/PHPMailerAutoload.php';
define('FROM', 'aseptik@gmail.com'); //email of sender
define('TO', 'XXXXXXX@XXXXX.com');//email of receiver
$client_email = 'XXXXX@developer.gserviceaccount.com';
$private_key = file_get_contents('tmp/XXXXXXX.p12');
$scopes = array(
'https://www.googleapis.com/auth/gmail.send',
'https://www.googleapis.com/auth/gmail.compose'
);
$credentials = new \Google_Auth_AssertionCredentials($client_email, $scopes, $private_key);
$credentials->sub = FROM;
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
function create_message() {
$mail = new PHPMailer();
$mail->setFrom(FROM, 'John Doe 1');
$mail->addAddress(TO, 'John Doe 2');
$mail->Subject = 'Saying Hello';
$mail->Body = 'This is a message just to say hello. So, "Hello"';
$mail->preSend();
$mime = $mail->getSentMIMEMessage();
return urlsafe_b64encode($mime);
}
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();
}
}
function urlsafe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array('+','/','=') , array('-','_','') , $data);
return $data;
}
$service = new \Google_Service_Gmail($client);
$msg = new \Google_Service_Gmail_Message();
$msg->setRaw(create_message());
sendMessage($service, 'me', $msg);
?>
我需要让我的服务帐户客户端正常工作的一件事是添加这个:
// you MUST do this to avoid 400 error
$user_to_impersonate = 'junk@example.net';
$client->setSubject($user_to_impersonate);
我希望下面的代码能够发送电子邮件,但我只收到了:
An error occurred: Error calling POST https://www.googleapis.com/gmail/v1/users/me/messages/send: (400) Bad Request
我使用底部的 Google 开发人员控制台 here 获得 200 OK
。有帮助吗?
$client_id = '599901532082-js1r50n20q6n5mir9fo1g81qkj9kfn3j.apps.googleusercontent.com';
$service_account_name = '599901532082-js1r50n20q6n5mir9fo1g81qkj9kfn3j@developer.gserviceaccount.com';
$key_file_location = '/tmp/APIProject-cb6558ba6435.p12';
$client = new \Google_Client();
$client->setApplicationName("Client_Library_Examples");
$service = new \Google_Service_Gmail($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new \Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.compose'),
$key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
//check if you want the validity of this string at: http://www.komeil.com/toolbox/base64decoder
//it is web safe base64 encoded email
$mime = "RnJvbTogSm9obiBEb2UgPHRpcmVuZ2FyZmlvQGdtYWlsLmVzPiANClRvOiBNYXJ5IFNtaXRoIDx0aXJlbmdhcmZpb0BnbWFpbC5jb20-IA0KU3ViamVjdDogU2F5aW5nIEhlbGxvIA0KRGF0ZTogRnJpLCAyMSBOb3YgMTk5NyAwOTo1NTowNiAtMDYwMCANCk1lc3NhZ2UtSUQ6IDwxMjM0QGxvY2FsLm1hY2hpbmUuZXhhbXBsZT4NCg0KVGhpcyBpcyBhIG1lc3NhZ2UganVzdCB0byBzYXkgaGVsbG8uIFNvLCAiSGVsbG8iLg==";
$service = new \Google_Service_Gmail($client);
$msg = new \Google_Service_Gmail_Message();
$msg->setRaw($mime);
try {
$results = $service->users_messages->send("me", $msg);
print 'Message with ID: ' . $message->getId() . ' sent.';
return $message;
} catch (\Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
编辑:
这是请求对象。它还包括响应数据:
object(Google_Http_Request)[508]
private 'batchHeaders' =>
array (size=3)
'Content-Type' => string 'application/http' (length=16)
'Content-Transfer-Encoding' => string 'binary' (length=6)
'MIME-Version' => string '1.0' (length=3)
protected 'queryParams' =>
array (size=0)
empty
protected 'requestMethod' => string 'POST' (length=4)
protected 'requestHeaders' =>
array (size=3)
'content-type' => string 'application/json; charset=UTF-8' (length=31)
'authorization' => string 'Bearer ya29.8gEUMiBLfxS8OLdSmpiQ-EcumeATo2qFAfPtPqwTw9fQ2zVrfZaA1X5OLoBmQccrXr8V8g' (length=82)
'accept-encoding' => string 'gzip' (length=4)
protected 'baseComponent' => string 'https://www.googleapis.com' (length=26)
protected 'path' => string '/gmail/v1/users/me/messages/send' (length=32)
protected 'postBody' => string '{"raw":"RnJvbTogSm9obiBEb2UgPHRpcmVuZ2FyZmlvQGdtYWlsLmVzPg0KVG86IE1hcnkgU21pdGggPHRpcmVuZ2FyZmlvQGdtYWlsLmNvbT4NClN1YmplY3Q6IFNheWluZyBIZWxsbw0KDQpUaGlzIGlzIGEgbWVzc2FnZSBqdXN0IHRvIHNheSBoZWxsby4gU28sICdIZWxsbycu"}' (length=214)
protected 'userAgent' => string 'Client_Library_Examples google-api-php-client/1.0.6-beta (gzip)' (length=63)
protected 'canGzip' => boolean true
protected 'responseHttpCode' => null
protected 'responseHeaders' => null
protected 'responseBody' => null
protected 'expectedClass' => string 'Google_Service_Gmail_Message' (length=28)
public 'accessKey' => null
object(Google_Http_Request)[508]
private 'batchHeaders' =>
array (size=3)
'Content-Type' => string 'application/http' (length=16)
'Content-Transfer-Encoding' => string 'binary' (length=6)
'MIME-Version' => string '1.0' (length=3)
protected 'queryParams' =>
array (size=0)
empty
protected 'requestMethod' => string 'POST' (length=4)
protected 'requestHeaders' =>
array (size=4)
'content-type' => string 'application/json; charset=UTF-8' (length=31)
'authorization' => string 'Bearer ya29.8gEUM***fxS8OLdSmpiQ-EcumeATo2qFAfPtPqwTw9fQ2zVrfZaA1X5OLoBmQccrXr8V8g' (length=82)
'accept-encoding' => string 'gzip' (length=4)
'content-length' => int 214
protected 'baseComponent' => string 'https://www.googleapis.com' (length=26)
protected 'path' => string '/gmail/v1/users/me/messages/send' (length=32)
protected 'postBody' => string '{"raw":"RnJvbTogSm9obiBEb2UgPHRpcmVuZ2FyZmlvQGdtYWlsLmVzPg0KVG86IE1hcnkgU21pdGggPHRpcmVuZ2FyZmlvQGdtYWlsLmNvbT4NClN1YmplY3Q6IFNheWluZyBIZWxsbw0KDQpUaGlzIGlzIGEgbWVzc2FnZSBqdXN0IHRvIHNheSBoZWxsby4gU28sICdIZWxsbycu"}' (length=214)
protected 'userAgent' => string 'Client_Library_Examples google-api-php-client/1.0.6-beta (gzip)' (length=63)
protected 'canGzip' => boolean true
protected 'responseHttpCode' => int 400
protected 'responseHeaders' =>
array (size=13)
'vary' => string 'Origin
X-Origin' (length=15)
'content-type' => string 'application/json; charset=UTF-8' (length=31)
'content-encoding' => string 'gzip' (length=4)
'date' => string 'Fri, 18 Sep 2015 08:34:25 GMT' (length=29)
'expires' => string 'Fri, 18 Sep 2015 08:34:25 GMT' (length=29)
'cache-control' => string 'private, max-age=0' (length=18)
'x-content-type-options' => string 'nosniff' (length=7)
'x-frame-options' => string 'SAMEORIGIN' (length=10)
'x-xss-protection' => string '1; mode=block' (length=13)
'server' => string 'GSE' (length=3)
'alternate-protocol' => string '443:quic,p=1' (length=12)
'alt-svc' => string 'quic=":443"; p="1"; ma=604800' (length=29)
'transfer-encoding' => string 'chunked' (length=7)
protected 'responseBody' => string '{
"error": {
"errors": [
{
"domain": "global",
"reason": "failedPrecondition",
"message": "Bad Request"
}
],
"code": 400,
"message": "Bad Request"
}
}
' (length=179)
protected 'expectedClass' => string 'Google_Service_Gmail_Message' (length=28)
public 'accessKey' => null
在字符串中使用 URL Endocde 和 url。
这个错误是space在url。
我认为您忘记了将 $client_id
分配给您的 $client
变量。
$client = new Google_Client();
$client->setApplicationName('Gmail API test');
$client->setDeveloperKey('<YOUR_API_KEY>');
$client->setClientSecret('<YOUR_CLIENT_SECRET>');
$client->SetClientId('599901532082-js1r50n20q6n5mir9fo1g81qkj9kfn3j.apps.googleusercontent.com');
$client->setScopes(array('https://www.googleapis.com/auth/gmail.send'));
$client->setAccessToken('{"access_token":"<YOUR_ACCESS_TOKEN>",
"token_type":"Bearer","expires_in":3600,
"refresh_token":"<YOUR_REFRESH_TOKEN>","created":12344556}');
$service = new Google_Service_Gmail($client);
$raw = "RnJvbTogSm9obiBEb2UgPHRpcmVuZ2FyZmlvQGdtYWlsLmVzPiANClRvOiBNYXJ5IFNtaXRoIDx0aXJlbmdhcmZpb0BnbWFpbC5jb20-IA0KU3ViamVjdDogU2F5aW5nIEhlbGxvIA0KRGF0ZTogRnJpLCAyMSBOb3YgMTk5NyAwOTo1NTowNiAtMDYwMCANCk1lc3NhZ2UtSUQ6IDwxMjM0QGxvY2FsLm1hY2hpbmUuZXhhbXBsZT4NCg0KVGhpcyBpcyBhIG1lc3NhZ2UganVzdCB0byBzYXkgaGVsbG8uIFNvLCAiSGVsbG8iLg==";
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($raw);
$results = $service->users_messages->send("me", $msg);
print 'Message with ID: ' . $message->getId() . ' sent.';
终于可以使用您的代码发送邮件了:
我认为您对 GMail API 有一点误解。
要使用它,您必须向 API 进行身份验证。为此,有两种方法:
- 使用 OAuth - 服务器将用户重定向到 google 的服务器,他们可以在其中登录、向您的应用授予权限,并将令牌传回给您
- 服务帐户。这些有点复杂:
- 首先,您必须设置一个应用程序(完成)
- 其次,您必须设置一个服务帐户。这就是您的应用向 google 进行身份验证的方式。你已经做到了,你得到的证书包含用于验证的私钥
- 第三,用户需要授予您的应用程序访问权限才能代表他们行事。这是你还没有完成的点。
那么您目前正在尝试从服务帐户发送邮件,但这不是 GMail 帐户。
Developer Console使用的是OAuth方式,试试这个没有问题。
另请注意:对于常规 GMail 帐户,您可以不使用'Service Accounts'。您将不得不使用 OAuth。 要使用服务帐户,您需要成为 Google Apps 客户。
我不会在这里转换 OAuth 授权,因为它完全不同,并且那里有很多 示例。
要授予您的服务帐户权限以代表您的 GMails/Google Apps 帐户发送邮件,请按照
this document。对于 One or More API Scopes
,您必须输入
https://mail.google.com/,https://www.googleapis.com/auth/gmail.modify,https://www.googleapis.com/auth/gmail.compose,https://www.googleapis.com/auth/gmail.send
.
设置完成后,就可以发送邮件了,修改代码如下:
$results = $service->users_messages->send("me", $msg);
不起作用,因为 'me' 指的是无法发送邮件的服务帐户(见上文)。
将 me
替换为应发送邮件的帐户的用户 ID(邮件地址)。:
$results = $service->users_messages->send("senders_mail@domain.com", $msg);
然后,您需要添加
$cred->sub = 'senders_mail@domain.com';
低于
$cred = new \Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.compose'),
$key
);
另请注意 $message
在 try...catch
-Block 中应该是 $msg
。
在下面,您会找到适合我的完整、有效的代码:
<?php
require_once realpath(dirname(__FILE__) . '/../src/Google/autoload.php');
$client_id = '*censored*.apps.googleusercontent.com';
$service_account_name = '*censored*@developer.gserviceaccount.com';
$key_file_location = '/tmp/apiKey.p12';
$userid_from='*censored*';
$client = new \Google_Client();
$client->setApplicationName("Client_Library_Examples");
//hmmm, really don't know whether these lines are necessary
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new \Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.compose', 'https://www.googleapis.com/auth/gmail.modify','https://www.googleapis.com/auth/gmail.readonly'),
$key
);
$cred->sub=$userid_from; //<-- Important!
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
//check if you want the validity of this string at: http://www.komeil.com/toolbox/base64decoder
//it is web safe base64 encoded email
$mime = "*censored*, same content as you posted, but another recipient ;-)";
$service = new \Google_Service_Gmail($client);
$msg = new \Google_Service_Gmail_Message();
$msg->setRaw($mime);
try {
$results = $service->users_messages->send($userid_from, $msg);
print 'Message with ID: ' . $results->id . ' sent.';
} catch (\Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
如果还有什么问题,欢迎随时提问!
这是一个完整的工作示例,只需确保更改所有适当的信息并使用PHPMailer 来格式化有效的邮件。
<?php
// this the link to gmail-api-client or whatever you have...
require 'vendor/autoload.php';
// download PHPMailer
// https://github.com/PHPMailer/PHPMailer and uncomment the line below.
// require 'PHPMailer/PHPMailerAutoload.php';
define('FROM', 'aseptik@gmail.com'); //email of sender
define('TO', 'XXXXXXX@XXXXX.com');//email of receiver
$client_email = 'XXXXX@developer.gserviceaccount.com';
$private_key = file_get_contents('tmp/XXXXXXX.p12');
$scopes = array(
'https://www.googleapis.com/auth/gmail.send',
'https://www.googleapis.com/auth/gmail.compose'
);
$credentials = new \Google_Auth_AssertionCredentials($client_email, $scopes, $private_key);
$credentials->sub = FROM;
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
function create_message() {
$mail = new PHPMailer();
$mail->setFrom(FROM, 'John Doe 1');
$mail->addAddress(TO, 'John Doe 2');
$mail->Subject = 'Saying Hello';
$mail->Body = 'This is a message just to say hello. So, "Hello"';
$mail->preSend();
$mime = $mail->getSentMIMEMessage();
return urlsafe_b64encode($mime);
}
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();
}
}
function urlsafe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array('+','/','=') , array('-','_','') , $data);
return $data;
}
$service = new \Google_Service_Gmail($client);
$msg = new \Google_Service_Gmail_Message();
$msg->setRaw(create_message());
sendMessage($service, 'me', $msg);
?>
我需要让我的服务帐户客户端正常工作的一件事是添加这个:
// you MUST do this to avoid 400 error
$user_to_impersonate = 'junk@example.net';
$client->setSubject($user_to_impersonate);