SendGrid is a popular cloud-based email delivery platform that allows you to send emails from your application. Laravel, a powerful PHP framework, has built-in support for SendGrid which simplifies the process of sending emails. In this blog post, we will walk you through the steps on how to configure and send emails using SendGrid in Laravel.
Prerequisites
Before getting started, make sure you have the following:
- Laravel application (you can create one using the laravel new command)
- SendGrid account (create a free account from the SendGrid website)
Step 1: Install SendGrid PHP Library
The first step is to install the SendGrid PHP library in your Laravel project. You can do this via composer using the following command:
composer require sendgrid/sendgrid
Step 2: Configure SendGrid
After installing the SendGrid PHP library, the next step is to configure SendGrid. In your .env file, set the following variables:
MAIL_MAILER=smtp MAIL_HOST=smtp.sendgrid.net MAIL_PORT=587 MAIL_USERNAME=apikey MAIL_PASSWORD=your_sendgrid_api_key MAIL_ENCRYPTION=tls MAIL_FROM_ADDRESS=your_email_address MAIL_FROM_NAME="${APP_NAME}"
Replace your_sendgrid_api_key with your actual SendGrid API key and your_email_address with the email address you want to send emails from.
Step 3: Create Mailable
In Laravel, emails are sent using mailables. Let’s create a new mailable called SendMail. You can create a new mailable using the following artisan command:
php artisan make:mail SendMail
Step 4: Send Email
Now that we’ve created our mailable, let’s use it to send an email. In your chosen controller, you can use the Mail::send method to send an email:
use Illuminate\Support\Facades\Mail; use App\Mail\SendMail; public function sendEmail() { $details = [ 'title' => 'Mail from SendGrid in Laravel', 'body' => 'This is for testing email using SendGrid in Laravel' ]; Mail::to('your_receiver_email_address')->send(new SendMail($details)); }
Replace your_receiver_email_address with the email address you want to send the email to.
Conclusion
That’s it! You’ve now configured SendGrid in your Laravel app and can send emails using SendGrid. With this setup, you can now easily send emails from your Laravel application, whether it’s for user registration confirmation, password reset, or any other scenario where email sending is needed.