Klasa działa na google workspace, nie wiem jak zadziała przy gmailu ale powinno działać tak samo.
<?php
namespace App\Libraries\Google;
use Google_Service_Gmail;
use Google_Service_Gmail_Message;
use Google_Service_Gmail_ModifyMessageRequest;
class GmailClient extends GoogleApiClient
{
public function sendMessage($to, $subject, $body, $filePath = null)
{
$service = new Google_Service_Gmail($this->client);
$user = 'me';
$boundary = uniqid(rand(), true);
$subjectBase64 = base64_encode($subject);
$rawMessage = "MIME-Version: 1.0\r\n";
$rawMessage .= 'To: ' . $to . "\r\n";
$rawMessage .= 'Subject: =?utf-8?B?' . $subjectBase64 . "?=\r\n";
$rawMessage .= "Content-Type: multipart/mixed; boundary={$boundary}\r\n";
$rawMessage .= "\r\n--{$boundary}\r\n";
$rawMessage .= "Content-Type: text/html; charset=utf-8\r\n";
$rawMessage .= "Content-Transfer-Encoding: base64\r\n\r\n";
$rawMessage .= chunk_split(base64_encode($body), 76, "\n");
if (!empty($filePath)) {
$fileData = base64_encode(file_get_contents($filePath));
$fileName = basename($filePath);
$rawMessage .= "\r\n--{$boundary}\r\n";
$rawMessage .= "Content-Type: application/octet-stream; name={$fileName}\r\n";
$rawMessage .= "Content-Transfer-Encoding: base64\r\n";
$rawMessage .= "Content-Disposition: attachment; filename={$fileName}\r\n\r\n";
$rawMessage .= chunk_split($fileData, 76, "\n");
}
$rawMessage .= "\r\n--{$boundary}--";
$rawData = rtrim(strtr(base64_encode($rawMessage), '+/', '-_'), '=');
$message = new Google_Service_Gmail_Message();
$message->setRaw($rawData);
$service->users_messages->send($user, $message);
}
}
Odświerzać token możesz w cronie i trzymać go na przykład w bazie. (chyba co godzine)
Jeżeli potrzebował byś api dla innej poczty lub reszty integracji mogę napisać.