Here are the steps to set up SendGrid email in Laravel:
-
Sign up for a SendGrid account and obtain an API key.
-
Add the SendGrid API key to your Laravel environment file (.env) by adding the following line:
SENDGRID_API_KEY=YOUR_SENDGRID_API_KEY
- In your Laravel project, install the official SendGrid library by running the following command in your terminal:
composer require sendgrid/sendgrid
-
Open the
config/mail.php
file and update the driver option to sendgrid. -
In the
config/services.php
file, add the following code to define the SendGrid API key:
'sendgrid' => [
'api_key' => env('SENDGRID_API_KEY'),
],
- To test the setup, you can use the following code in a controller or route:
use Illuminate\Support\Facades\Mail;
$data = [
'email' => '[email protected]',
'name' => 'Test User',
'subject' => 'Test email from SendGrid',
'body' => 'This is a test email sent from SendGrid.',
];
Mail::send('emails.test', $data, function ($message) use ($data) {
$message->to($data['email'], $data['name'])->subject($data['subject']);
});
This should send an email using SendGrid. If everything is set up correctly, you should receive an email with the message "This is a test email sent from SendGrid."
Note: You might need to create an email view file (e.g., resources/views/emails/test.blade.php)
to render the content of the email.