Gmail API:尝试发送电子邮件时出现400个错误的请求(PHP代码) [英] Gmail API: 400 bad request when trying to send an email (PHP code)

查看:1985
本文介绍了Gmail API:尝试发送电子邮件时出现400个错误的请求(PHP代码)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期望下面的代码发送电子邮件,但我只是得到这个:


发生错误:错误调用POST
https://www.googleapis.com/gmail/v1/users/me/消息/发送:(400)错误
请求


我得到 200确定使用Google Developers Console 此处

  $ 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);
$ b $ if($ client-> getAuth() - > isAccessTokenExpired()){
$ client-> getAuth() - > refreshTokenWithAssertion($ cred);
}
//检查您是否想要此字符串的有效性:http://www.komeil.com/toolbox/base64decoder
//它是web安全的base64编码电子邮件
$的mime = RnJvbTogSm9obiBEb2UgPHRpcmVuZ2FyZmlvQGdtYWlsLmVzPiANClRvOiBNYXJ5IFNtaXRoIDx0aXJlbmdhcmZpb0BnbWFpbC5jb20-IA0KU3ViamVjdDogU2F5aW5nIEhlbGxvIA0KRGF0ZTogRnJpLCAyMSBOb3YgMTk5NyAwOTo1NTowNiAtMDYwMCANCk1lc3NhZ2UtSUQ6IDwxMjM0QGxvY2FsLm1hY2hpbmUuZXhhbXBsZT4NCg0KVGhpcyBpcyBhIG1lc3NhZ2UganVzdCB0byBzYXkgaGVsbG8uIFNvLCAiSGVsbG8iLg ==;


$ service = new \Google_Service_Gmail($ client);

$ msg = new \Google_Service_Gmail_Message();
$ msg-> setRaw($ mime);
$ b try {
$ results = $ service-> users_messages-> send(me,$ msg);
print'带ID的消息:'。 $ message-> getId()。 '发送'。
返回$ message;
} catch(\Exception $ e){
print'发生错误:'。 $ E->的getMessage();




编辑:



这是请求对象。它还包括响应数据:

  object(Google_Http_Request)[508] 
private'batchHeaders'=>
array(size = 3)
'Content-Type'=>字符串'application / http'(长度= 16)
'Content-Transfer-Encoding'=>字符串'binary'(长度= 6)
'MIME-Version'=>字符串'1.0'(长度= 3)
保护'queryParams'=>
array(size = 0)
empty
protected'requestMethod'=>字符串'POST'(长度= 4)
保护'requestHeaders'=>
array(size = 3)
'content-type'=>字符串'application / json; charset = UTF-8'(长度= 31)
'authorization'=>字符串'承载者ya29.8gEUMiBLfxS8OLdSmpiQ-EcumeATo2qFAfPtPqwTw9fQ2zVrfZaA1X5OLoBmQccrXr8V8g'(长度= 82)
'accept-encoding'=>字符串'gzip'(长度= 4)
保护'baseComponent'=>字符串'https://www.googleapis.com'(长度= 26)
保护'路径'=>字符串'/ gmail / v1 / users / me / messages / send'(长度= 32)
保护'postBody'=>字符串{ 原始: RnJvbTogSm9obiBEb2UgPHRpcmVuZ2FyZmlvQGdtYWlsLmVzPg0KVG86IE1hcnkgU21pdGggPHRpcmVuZ2FyZmlvQGdtYWlsLmNvbT4NClN1YmplY3Q6IFNheWluZyBIZWxsbw0KDQpUaGlzIGlzIGEgbWVzc2FnZSBqdXN0IHRvIHNheSBoZWxsby4gU28sICdIZWxsbycu}(长度= 214)
保护的userAgent => string'Client_Library_Examples google-api-php-client / 1.0.6-beta(gzip)'(length = 63)
protected'canGzip'=>布尔值true
protected'responseHttpCode'=> null
protected'responseHeaders'=> null
保护'responseBody'=> null
保护'expectedClass'=>字符串'Google_Service_Gmail_Message'(长度= 28)
public'accessKey'=> null

object(Google_Http_Request)[508]
private'batchHeaders'=>
array(size = 3)
'Content-Type'=>字符串'application / http'(长度= 16)
'Content-Transfer-Encoding'=>字符串'binary'(长度= 6)
'MIME-Version'=>字符串'1.0'(长度= 3)
保护'queryParams'=>
array(size = 0)
empty
protected'requestMethod'=>字符串'POST'(长度= 4)
保护'requestHeaders'=>
array(size = 4)
'content-type'=>字符串'application / json; charset = UTF-8'(长度= 31)
'authorization'=> string'Bearer ya29.8gEUM *** fxS8OLdSmpiQ-EcumeATo2qFAfPtPqwTw9fQ2zVrfZaA1X5OLoBmQccrXr8V8g'(length = 82)
'accept-encoding'=>字符串'gzip'(长度= 4)
'content-length'=> int 214
protected'baseComponent'=>字符串'https://www.googleapis.com'(长度= 26)
保护'路径'=>字符串'/ gmail / v1 / users / me / messages / send'(长度= 32)
保护'postBody'=>字符串{ 原始: RnJvbTogSm9obiBEb2UgPHRpcmVuZ2FyZmlvQGdtYWlsLmVzPg0KVG86IE1hcnkgU21pdGggPHRpcmVuZ2FyZmlvQGdtYWlsLmNvbT4NClN1YmplY3Q6IFNheWluZyBIZWxsbw0KDQpUaGlzIGlzIGEgbWVzc2FnZSBqdXN0IHRvIHNheSBoZWxsby4gU28sICdIZWxsbycu}(长度= 214)
保护的userAgent => string'Client_Library_Examples google-api-php-client / 1.0.6-beta(gzip)'(length = 63)
protected'canGzip'=>布尔值true
protected'responseHttpCode'=> int 400
protected'responseHeaders'=>
array(size = 13)
'vary'=>字符串'Origin
X-Origin'(长度= 15)
'content-type'=>字符串'application / json; charset = UTF-8'(长度= 31)
'content-encoding'=>字符串'gzip'(长度= 4)
'date'=> 'Fri,18 Sep 2015 08:34:25 GMT'(length = 29)
'expires'=> 'Fri,18 Sep 2015 08:34:25 GMT'(length = 29)
'cache-control'=> string'private,max-age = 0'(length = 18)
'x-content-type-options'=>字符串'nosniff'(长度= 7)
'x-frame-options'=>字符串'SAMEORIGIN'(长度= 10)
'x-xss-protection'=>字符串'1; mode = block'(length = 13)
'server'=>字符串'GSE'(长度= 3)
'alternate-protocol'=>字符串'443:quic,p = 1'(长度= 12)
'alt-svc'=>字符串'quic =:443; p值= 1; ma = 604800'(长度= 29)
'transfer-encoding'=>字符串'chunked'(长度= 7)
保护'responseBody'=>字符串'{
错误:{
错误:[
{
domain:global,
reason:failedPrecondition,
message:Bad Request
}
],
code:400,
message:Bad Request
}
}
'(长度= 179)
保护'expectedClass'=>字符串'Google_Service_Gmail_Message'(长度= 28)
public'accessKey'=> null


解决方案

终于要发送邮件给您的代码:



我认为你误解了一些GMail API。

要使用它,必须验证API。要做到这一点,有两种方法:


  • 使用OAuth - 服务器将用户重定向到谷歌服务器,他们可以登录,授予权限到您的应用程序,并将令牌传回给您

  • 服务帐户。这些有点复杂:


    • 首先,您必须设置一个应用程序(完成)
    • 其次,你将不得不建立一个服务帐户。这就是您的应用向Google进行身份验证的方式。您已经完成了这项工作,并且您获得的证书包含要验证的私钥
    • 第三,用户需要授予您的应用程序访问权限以代表它们执行操作。这是您尚未完成的要点。 目前尝试从服务帐户发送邮件,但这不是 GMail帐户。



      开发者控制台使用OAuth方法,所以这是没有问题的。



      请注意:使用普通的Gmail帐户,您可以不使用服务帐户。你必须使用OAuth。
      要使用服务帐户,您需要成为Google Apps客户。



      我不会在这里获得OAuth授权,因为它完全不同,

      要授权您的服务帐户权限代表您的GMails / Google Apps帐户发送邮件,请按照
      此文档。对于一个或多个API范围,您必须输入
      https://mail.google.com/,http:// /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 替换为发送邮件的帐户的用户标识(邮件地址):


        $ 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);


      //嗯,真的不知道这些行是否必要
      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; //< - 重要!
      $ client-> setAssertionCredentials($ cred);
      $ b $ if($ client-> getAuth() - > isAccessTokenExpired()){
      $ client-> getAuth() - > refreshTokenWithAssertion($ cred);
      }

      //检查你想要这个字符串的有效性:http://www.komeil.com/toolbox/base64decoder
      //它是web安全的base64编码的电子邮件
      $ mime =*已审查*,与您发布的内容相同,但另一收件人;-);


      $ service = new \Google_Service_Gmail($ client);

      $ msg = new \Google_Service_Gmail_Message();
      $ msg-> setRaw($ mime); ($ userid_from,$ msg);


      print'带ID的消息:'。 $ results-> id。 '发送'。
      } catch(\Exception $ e){
      print'发生错误:'。 $ E->的getMessage();
      }

      如果还有问题,请随时询问!


      I expected the code below to send an email, but I'm only getting this:

      An error occurred: Error calling POST https://www.googleapis.com/gmail/v1/users/me/messages/send: (400) Bad Request

      I get a 200 OK using the Google Developers Console here at the bottom. Any help?

      $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();
      
      }
      

      EDIT:

      this is the request object. It includes the response data also:

      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
      

      解决方案

      finally got to send Mails with your code:

      I think you have misunderstood the GMail API a little bit.

      To use it, you must authenticate to the API. To do this, there are two ways:

      • use OAuth - the Server redirects the user to google's servers, where they can login, grant permission to your app, and pass a token back to you
      • Service Accounts. These are a little bit more complicated:
        • First, you'll have to setup an app (done)
        • second, you'll have to setup a service account. This is how your app authenticates to google. you've done that, and the certificate you've got contains the private key to authenticate
        • third, the user needs to grant your application access to act on behalf of them. This is the point you haven't done yet.

      So what you're currently trying is to send mails from the service account, but this is not an GMail Account.

      The Developer Console uses the OAuth method, so there's no problem to try this.

      Please also note: With regular GMail Accounts, you can not use 'Service Accounts'. You'll have to use OAuth. To use Service Accounts, you need to be a Google Apps customer.

      I won't conver OAuth authorization here, because it's completely different, and there are many examples out there.

      To grant your Service Account Permissions to send mails on behalf of your GMails/Google Apps accounts, please follow this document. For One or More API Scopes, you'll have to enter 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.

      After you've setup this, it's possible to send mails, just modify the code as follows:

      $results = $service->users_messages->send("me", $msg);
      

      won't work, because 'me' referrs to the service account, which can't send mail (see above). Replace me with the user id (mail-address) of the account from which the mails should be send.:

      $results = $service->users_messages->send("senders_mail@domain.com", $msg);
      

      Then, you'll need to add

      $cred->sub = 'senders_mail@domain.com';
      

      below

      $cred = new \Google_Auth_AssertionCredentials(
        $service_account_name,
        array('https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.compose'),
        $key
      );
      

      Please also note that $message should be $msg in the try...catch-Block.

      Below, you'll find the the complete, working code for me:

      <?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();
      }
      

      If there are any questions left, feel free to ask!

      这篇关于Gmail API:尝试发送电子邮件时出现400个错误的请求(PHP代码)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆