To use Gmail with Laravel's mailer now that Google has deprecated the use of username and password authentication, you should use OAuth 2.0 for authentication. Here's a step-by-step guide on how to set this up:
-
Create a Google Cloud Project:
- Go to the Google Cloud Console.
- Create a new project.
- Navigate to the "Credentials" section.
- Click on "Create Credentials" and select "OAuth 2.0 Client IDs".
- Configure the consent screen and set up the OAuth 2.0 client ID.
-
Enable Gmail API:
- In the Google Cloud Console, go to the "Library" section.
- Search for "Gmail API" and enable it for your project.
-
Set Up OAuth 2.0 Credentials:
- Download the
credentials.jsonfile from the Google Cloud Console. - Store this file securely in your Laravel project.
- Download the
-
Install Required Packages:
-
Use a package like
league/oauth2-googleto handle OAuth 2.0 authentication. -
Install it via Composer:
composer require league/oauth2-google
-
-
Configure Laravel to Use OAuth 2.0:
-
Update your
.envfile with the necessary configuration:MAIL_MAILER=smtp MAIL_HOST=smtp.gmail.com MAIL_PORT=587 MAIL_ENCRYPTION=tls [email protected] MAIL_PASSWORD=your-oauth2-access-token -
Note: You will need to generate an OAuth 2.0 access token and refresh token using the
league/oauth2-googlepackage.
-
-
Generate Access and Refresh Tokens:
-
Use the following script to generate the tokens:
use League\OAuth2\Client\Provider\Google; $provider = new Google([ 'clientId' => 'your-client-id', 'clientSecret' => 'your-client-secret', 'redirectUri' => 'your-redirect-uri', ]); if (!isset($_GET['code'])) { $authUrl = $provider->getAuthorizationUrl(); $_SESSION['oauth2state'] = $provider->getState(); header('Location: ' . $authUrl); exit; } elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { unset($_SESSION['oauth2state']); exit('Invalid state'); } else { $token = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]); echo 'Access Token: ' . $token->getToken(); echo 'Refresh Token: ' . $token->getRefreshToken(); } -
Replace
'your-client-id','your-client-secret', and'your-redirect-uri'with your actual credentials.
-
-
Use the Access Token in Laravel:
- Once you have the access token, use it in your
.envfile as shown above.
- Once you have the access token, use it in your
-
Handle Token Refresh:
- Implement logic to refresh the access token using the refresh token when it expires.
By following these steps, you can configure Laravel to send emails using Gmail with OAuth 2.0 authentication. This approach is more secure and aligns with Google's current authentication policies.