To send emails in Yii2 using Google’s OAuth 2.0 protocol, follow these steps:
Step 1: Create a Google API Project
- Go to the Google Cloud Console.
- Create a new project or select an existing one.
- Navigate to the API & Services > Credentials section.
- Click Create Credentials and choose OAuth 2.0 Client IDs.
- Configure the consent screen if prompted.
- Set up OAuth 2.0 credentials, specifying the redirect URIs and permissions.
- Save the Client ID and Client Secret.
Step 2: Install Google API Client for PHP
Install the required Google API client library via Composer:
Step 3: Configure Yii2 for Gmail OAuth2
- In your Yii2 project, configure your mailer component to use Gmail’s SMTP with OAuth 2.0:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@app/mail',
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'your-email@gmail.com',
'password' => 'your-oauth2-token', // You will generate this in the next step
'port' => '587',
'encryption' => 'tls',
],
],
Step 4: Obtain OAuth 2.0 Token
Use the Google API Client to get an OAuth 2.0 token. In your Yii2 controller or a separate script:
$client = new Google_Client();
$client->setClientId('your-client-id');
$client->setClientSecret('your-client-secret');
$client->setRedirectUri('your-redirect-uri');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->addScope(Google_Service_Gmail::MAIL_GOOGLE_COM);$authUrl = $client->createAuthUrl();echo “Open the following link in your browser:\n$authUrl\n”;
// After user consents, they will get a code in the redirect URL
$authCode = ‘authorization-code-here’;
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
// Save the access token for future use
$client->setAccessToken($accessToken);
Step 5: Send Emails
Once you have the access token, you can use the Gmail API or SMTP to send emails. You need to update the password field in your mailer configuration to use the OAuth token.

Leave a Reply