通过Google API发送电子邮件 [英] Send email by Google API

查看:123
本文介绍了通过Google API发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I trying to send an email using Google API

发送电子邮件控制器外观

Send email controller look as

    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类:

getClient class:

    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;
    }

当我尝试运行此程序时,我收到错误消息:

When I'm trying to run this I receiving error:

{ "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" } } 

credentials.json

credentials.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时,它会显示所需的数据.还是我应该如何登录才能正确使用它而不会受到干扰?我之前(几个小时前)已经登录.

What can be wrong with my code? When I'm trying to print out $client it displays required data. Or how I shall to login to use it properly without interruptions? I've logged in before(several hours ago).

推荐答案

似乎您缺少获取和/或设置访问令牌或刷新令牌的步骤.在 PHP Gmail快速入门中,这是这段代码:

It looks like you're missing the step where you obtain and/or set the access token or refresh token. In the PHP Quickstart for Gmail, it's this chunk of code:

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}

稍微细分一下:

  1. 您需要通过将用户发送到授权URL( $ client-> createAuthUrl())来请求用户授权
  2. 然后将代码交换为访问令牌( $ client-> fetchAccessTokenWithAuthCode($ authCode))
  3. 然后将其设置在客户端上( $ client-> setAccessToken($ accessToken))或保存以备将来使用.
  1. You need to request authorization from the user by sending them to the authorization URL ($client->createAuthUrl())
  2. then exchange the code for an access token ($client->fetchAccessTokenWithAuthCode($authCode))
  3. and either set it on your client ($client->setAccessToken($accessToken)) or save it for future use.

除了访问令牌外,您还需要保存返回的刷新令牌,这样就不必每次都重新登录( $ client-> fetchAccessTokenWithRefreshToken($ refreshToken)).如果您已经完成了此过程,则访问令牌可能已过期,您需要使用刷新令牌或重新进行身份验证才能再次获得访问权限.

In addition to the access token, you'll also want to save the refresh token that gets returned so you don't have to re-login every time ($client->fetchAccessTokenWithRefreshToken($refreshToken)). If you've gone through this process already, it's possible that your access token expired and you need to either use the refresh token or re-authenticate to get access again.

如果您正在为不只是您自己的用户开发此应用程序,则可能需要研究托管的OAuth平台(例如Xkit)a>,我在哪里工作.他们处理获得授权,刷新令牌等的过程,以及对令牌进行加密并为每个用户存储它们的过程.

If you're developing this application for more users than just yourself, you may want to look into managed OAuth platforms like Xkit, where I work. They handle the process of getting authorization, refreshing tokens, etc, along with encrypting the tokens and storing them for each individual user.

这篇关于通过Google API发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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