0

I'm trying to develop a web application that send email throught Gmail API. But I'm getting this error

Fatal error: Uncaught Error: Class 'Google_Service_Gmail_Message' not found in /var/www/html/wordpress/multi_users/approval.php:18 Stack trace: #0 {main} thrown in /var/www/html/wordpress/multi_users/approval.php on line 18

approval.php

<?php
// include your composer dependencies
require_once '/../../gmail/vendor/autoload.php';


// ERRORS
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$user = 'me';
$strSubject = 'Test mail using GMail API' . date('M d, Y h:i:s A');
$strRawMessage = "From: myAddress<hub@gmail.com>\r\n";
$strRawMessage .= "To: toAddress <san@gmail.com>\r\n";
$strRawMessage .= 'Subject: =?utf-8?B?' . base64_encode($strSubject) . "?=\r\n";
$strRawMessage .= "MIME-Version: 1.0\r\n";
$strRawMessage .= "Content-Type: text/html; charset=utf-8\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
$strRawMessage .= "this <b>is a test message!\r\n";
// The message needs to be encoded in Base64URL
$mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($mime);
//The special value **me** can be used to indicate the authenticated user.
$service->users_messages->send("me", $msg);

I found the code above to send the email, but I'm sure it is missing some lines. The API has just been installed and should be working fine. The error comes from this line: $msg = new Google_Service_Gmail_Message();

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449

2 Answers2

1

Try running this command in terminal of the project folder: composer dump-autoload

Regards

Eliasu
  • 79
  • 2
  • Hii, I tried the suggestion and now I got: - Trying to get property 'users_messages' of non-object on line 25 - Uncaught Error: Call to a member function send() on null –  Sep 16 '20 at 01:43
  • Ok then it means the class can now be found, and it instantiated. About the current error, check that the $service variable is set and that it has 'user_messages' property before calling '$service->users_messages->send("me", $msg);'. – Eliasu Sep 17 '20 at 07:54
0

Solution

You are missing the Gmail service set up. Once you fixed the dependencies thanks to @Eliasu help, you will have to insert the code to build and set up the Gmail Service.

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Gmail($client);

The getClient() function will depend on how you will run this application:

If it's a server application you will need a Service Account client, otherwise you can use the getClient() function posted in the Gmail API PHP Quickstart.

Reference

Service Accounts

PHP Service Account Client

Gmail API

Alessandro
  • 2,848
  • 1
  • 8
  • 16