<?php
 use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\OAuth; use League\OAuth2\Client\Provider\Google AS GoogleProvider; class vB_Mail_Transport_PhpMailer_Gmail extends vB_Mail_Transport_PhpMailer { public function getAuthorizationUrl(string $redirectUrl) : array { $provider = $this->getOauthProvider([ 'redirectUri' => $redirectUrl, 'accessType' => 'offline', ]); $url = $provider->getAuthorizationUrl([ 'prompt' => 'consent', 'scope' => [ 'https://mail.google.com/' ], ]); $state = $provider->getState(); return [$url, $state]; } public function getRefreshToken(string $code, string $redirectUrl) : string { $provider = $this->getOauthProvider([ 'redirectUri' => $redirectUrl, 'accessType' => 'offline', ]); $token = $provider->getAccessToken('authorization_code', ['code' => $code]); return $token->getRefreshToken(); } protected function createPhpMailer() : PHPMailer { $vboptions = vB::getDatastore()->getValue('options'); $mailer = parent::createPhpMailer(); $mailer->isSMTP(); $mailer->Port = 465; $mailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; $mailer->Host = 'smtp.gmail.com'; $mailer->SMTPAuth = true; $mailer->AuthType = 'XOAUTH2'; $options = [ 'provider' => $this->getOauthProvider([]), 'clientId' => $vboptions['email_gmail_clientid'], 'clientSecret' => $vboptions['email_gmail_clientsecret'], 'refreshToken' => $vboptions['email_gmail_refreshtoken'], 'userName' => $vboptions['webmasteremail'], ]; $mailer->setOAuth(new vB_Mail_Transport_PhpMailer_CachingOauth($options, 'gmail_accesstoken')); return $mailer; } private function getOauthProvider(array $options) : GoogleProvider { $vboptions = vB::getDatastore()->getValue('options'); $options['clientId'] = $vboptions['email_gmail_clientid']; $options['clientSecret'] = $vboptions['email_gmail_clientsecret']; return new GoogleProvider($options); } } 