通过 Google API 发送电子邮件

时间:2021-01-13 16:48:46

标签: php google-api google-oauth gmail-api google-api-php-client

我尝试使用 Google API 发送电子邮件

发送电子邮件控制器看起来像

    public function sendMessage()
    {
        $client = self::getClient();
        $service = new Google_Service_Gmail($client);
        $mailer = $service->users_messages;

        $message = (new \Swift_Message('Here is my subject'))
            ->setFrom('myemailaddress@myserver.com')
            ->setTo(['receiver@someserver.com' => 'Test Name'])
            ->setContentType('text/html')
            ->setCharset('utf-8')
            ->setBody('<h4>Here is my body</h4>');

        $msg_base64 = (new \Swift_Mime_ContentEncoder_Base64ContentEncoder())
            ->encodeString($message->toString());

        $message = new Google_Service_Gmail_Message();
        $message->setRaw($msg_base64);
        $message = $mailer->send('me', $message);
        print_r($message);
    }

getClient 类:

    function getClient()
    {
        $client = new Google_Client();
        $client->setRedirectUri('http://' . 'site.com' . '/oauth2callback.php');
        $client->setApplicationName('Gmail API PHP');
        $client->setScopes(Google_Service_Gmail::GMAIL_READONLY);
        $client->setAuthConfig('credentials.json');
        $client->setAccessType('offline');
        $client->setPrompt('select_account consent');
        return $client;
    }

当我尝试运行它时,我收到错误:

{ "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Login Required.", "domain": "global", "reason": "required", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED" } } 

凭证.json

{"web":{
  "client_id":"REDACTED",
  "project_id":"project-44",
  "auth_uri":"https://accounts.google.com/o/oauth2/auth",
  "token_uri":"https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
  "client_secret":"redacted",
  "access_token":"redacted"}}

我的代码有什么问题?当我尝试打印 $client 时,它会显示所需的数据。或者我应该如何登录以正确使用它而不会中断?我之前(几个小时前)登录过。

0 个答案:

没有答案
相关问题