Send email results in "missing required authentication"

I’m new to this API and currently trying to send email by Gmail. I have Laravel installed and required by composer google/apiclient:"^2.7".

That’s how I call create message and send functions

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

class to create message for 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}>rn";
        $rawMessageString .= "To: <{$to}>rn";
        $rawMessageString .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($subject) . "?=rn";
        $rawMessageString .= "MIME-Version: 1.0rn";
        $rawMessageString .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "rn";
        $rawMessageString .= "rn--{$boundary}rn";
        $rawMessageString .= 'Content-Type: text/html; charset=' . $charset . "rn";
        $rawMessageString .= "Content-Transfer-Encoding: base64" . "rnrn";
        $rawMessageString .= str_replace("n","",$messageBody)."rn";
        $rawMessageString .= "--{$boundary}rn";

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

class to send email:

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

But for some reason when I trying to pull this out it responds with

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

I’m sorta stuck. Can you elaborate what it does want from me? ID of client was provided, though it says I’m not unauthenticated.

Source: Ask PHP

LEAVE A COMMENT