【问题标题】:Send email results in "missing required authentication"发送电子邮件导致“缺少所需的身份验证”
【发布时间】:2021-04-18 14:03:03
【问题描述】:

我是此 API 的新手,目前正在尝试通过 Gmail 发送电子邮件。我已经安装了 Laravel,并且 composer google/apiclient:"^2.7" 需要它。

这就是我如何调用创建消息和发送函数

        $message = $this->googleApi->createMessage($user->name, $user->email, 'An email', $text);

        $client = new Google_Client();
        $service = new Google_Service_Gmail($client);
        $userId = 'my-google-id.apps.googleusercontent.com'

        $sendMessage = $this->googleApi->sendMessage($service, $userid, $message);

为 API 创建消息的类:

 public function createMessage($sender, $to, $subject, $messageText)
    {
        $message = new Google_Service_Gmail_Message();
        $subjectCharset = $charset = 'utf-8';


        $messageBody = 'Hello';
        $boundary = uniqid(rand(), true);
        $rawMessageString = "From: <{$sender}>\r\n";
        $rawMessageString .= "To: <{$to}>\r\n";
        $rawMessageString .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($subject) . "?=\r\n";
        $rawMessageString .= "MIME-Version: 1.0\r\n";
        $rawMessageString .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n";
        $rawMessageString .= "\r\n--{$boundary}\r\n";
        $rawMessageString .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
        $rawMessageString .= "Content-Transfer-Encoding: base64" . "\r\n\r\n";
        $rawMessageString .= str_replace("\n","",$messageBody)."\r\n";
        $rawMessageString .= "--{$boundary}\r\n";

        $rawMessage = rtrim(strtr(base64_encode($rawMessageString), '+/', '-_'), '=');
        $message->setRaw($rawMessage);
        return $message;
    }

发送电子邮件的类:

    public function sendMessage($service, $userId, $message)
    {
        try {
            $request = $service->users_messages->send($userId, $message);
            return $request;
        } catch (Exception $e) {
            return 'An error occurred: ' . $e->getMessage();
        }
    }

但由于某种原因,当我试图将其拉出时,它会响应

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

我有点卡住了。你能详细说明它想从我这里得到什么吗?提供了客户的 ID,但它说我不是未经身份验证的。

【问题讨论】:

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


    【解决方案1】:

    您需要正确初始化 Google_client PHP quick start。如果它没有弹出并请求授权,那么它就不能正常工作。

    我建议先从快速入门开始。一旦你有这个工作,你应该能够改变它来发送邮件,而不仅仅是列出标签。

    <?php
    require __DIR__ . '/vendor/autoload.php';
    
    if (php_sapi_name() != 'cli') {
        throw new Exception('This application must be run on the command line.');
    }
    
    /**
     * Returns an authorized API client.
     * @return Google_Client the authorized client object
     */
    function getClient()
    {
        $client = new Google_Client();
        $client->setApplicationName('Gmail API PHP Quickstart');
        $client->setScopes(Google_Service_Gmail::GMAIL_READONLY);
        $client->setAuthConfig('credentials.json');
        $client->setAccessType('offline');
        $client->setPrompt('select_account consent');
    
        // 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;
    }
    
    
    // Get the API client and construct the service object.
    $client = getClient();
    $service = new Google_Service_Gmail($client);
    
    // Print the labels in the user's account.
    $user = 'me';
    $results = $service->users_labels->listUsersLabels($user);
    
    if (count($results->getLabels()) == 0) {
      print "No labels found.\n";
    } else {
      print "Labels:\n";
      foreach ($results->getLabels() as $label) {
        printf("- %s\n", $label->getName());
      }
    }
    

    验证

    关于 gmail api 和发送邮件范围的注意事项。此范围的验证需要时间,因为它是由第三方公司完成的。我建议你早点开始。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 2017-09-07
    • 2013-11-30
    • 1970-01-01
    相关资源
    最近更新 更多