To implement Gmail API OAuth and fetch a list of emails with filtering using the dacastro4/laravel-gmail package, follow these steps:
-
Install the Package: First, you need to install the
dacastro4/laravel-gmailpackage via Composer:composer require dacastro4/laravel-gmail -
Publish the Configuration: Publish the configuration file to set up the necessary configurations:
php artisan vendor:publish --provider="Dacastro4\LaravelGmail\LaravelGmailServiceProvider" -
Set Up Google API Credentials:
- Go to the Google Cloud Console.
- Create a new project or select an existing one.
- Enable the Gmail API for your project.
- Create OAuth 2.0 credentials and download the
credentials.jsonfile. - Place the
credentials.jsonfile in thestorage/app/gmaildirectory of your Laravel project.
-
Configure the
.envFile: Add the following environment variables to your.envfile:GMAIL_CLIENT_ID=your-client-id GMAIL_CLIENT_SECRET=your-client-secret GMAIL_REDIRECT_URI=your-redirect-uri -
Authenticate the User: Create a route and controller method to handle the OAuth authentication:
// routes/web.php Route::get('auth/gmail', 'GmailController@redirectToGoogle'); Route::get('auth/gmail/callback', 'GmailController@handleGoogleCallback');// app/Http/Controllers/GmailController.php namespace App\Http\Controllers; use Illuminate\Http\Request; use LaravelGmail; class GmailController extends Controller { public function redirectToGoogle() { return LaravelGmail::redirect(); } public function handleGoogleCallback() { LaravelGmail::makeToken(); return redirect()->to('/'); // Redirect to your desired route } } -
Fetch Emails with Filtering: Once authenticated, you can fetch emails with specific filters. For example, to fetch unread emails:
// app/Http/Controllers/GmailController.php namespace App\Http\Controllers; use Illuminate\Http\Request; use LaravelGmail; class GmailController extends Controller { public function listUnreadEmails() { $messages = LaravelGmail::message()->unread()->all(); foreach ($messages as $message) { $subject = $message->getSubject(); $body = $message->getPlainTextBody(); // Process the email as needed } return view('emails.list', compact('messages')); } }Add a route to access this method:
// routes/web.php Route::get('emails/unread', 'GmailController@listUnreadEmails'); -
View the Emails: Create a view to display the emails:
<!-- resources/views/emails/list.blade.php --> <!DOCTYPE html> <html> <head> <title>Unread Emails</title> </head> <body> <h1>Unread Emails</h1> <ul> @foreach ($messages as $message) <li>{{ $message->getSubject() }}</li> @endforeach </ul> </body> </html>
By following these steps, you should be able to implement Gmail API OAuth and fetch a list of emails with filtering using the dacastro4/laravel-gmail package. Make sure to handle exceptions and errors appropriately in a production environment.