In the age of digital communication, email sending is a fundamental aspect of nearly all web applications. Laravel, known for its strong PHP framework, offers a highly effective interface for sending emails through a variety of services. In this blog post, we will provide a tutorial on utilizing SendGrid, a widely used cloud-based email delivery service, for sending emails in Laravel.
Prerequisites
- A Laravel application setup
- SendGrid account
Step 1: Install Guzzle, a PHP HTTP Client
Laravel uses Guzzle for HTTP requests. Install it via Composer:
composer require guzzlehttp/guzzle
Step 2: Configure SendGrid API Key
In your SendGrid account, create an API key. In your Laravel app, open the .env file and set the SendGrid API key as follows:
SENDGRID_API_KEY='your_sendgrid_api_key'
Step 3: Configure Laravel to Use SendGrid
Update the config/mail.php file as follows:
'mailers' => [ ... 'sendgrid' => [ 'transport' => 'sendgrid', ], ],
Next, create a new service provider:
php artisan make:provider SendGridServiceProvider
In the SendGridServiceProvider (app/Providers/SendGridServiceProvider.php), register a new mail transport as follows:
$this->app['swift.transport']->extend('sendgrid', function ($config) { return new \SendGridTransport(new \GuzzleHttp\Client, env('SENDGRID_API_KEY')); });
Step 4: Send Emails
With SendGrid setup, you can now send emails. Here is a simple example:
$data = ['message' => 'Hello World!']; Mail::send('emails.test', $data, function ($message) { $message->to('test@example.com', 'John Doe')->subject('Test Email'); });
Make sure to replace ‘test@example.com’ and ‘John Doe’ with the recipient’s email and name, respectively.
Conclusion
That’s it! You’ve successfully configured your Laravel application to send emails using SendGrid. SendGrid not only allows you to send emails but also provides additional features like tracking, analytics, etc., helping you to enhance your email system’s functionality.