Home » Laravel » How to Use SendGrid API in Laravel

How to Use SendGrid API in Laravel

SendGrid is the most popular service for sending email messages. If you want to send fewer emails, you can use it for free. SendGrid provides an SMTP API, so there is no problem using this service in Laravel.

In this short article we will explain how to use the SendGrid API in Laravel. We will show you how to get the API key and how to fill in mail settings in the Laravel .env file.


Table of Contents

Using SendGrid API in Laravel

1. Getting API Key

First, you should generate an API key in the SendGrid interface. Open Settings -> API Keys:

Here, click the button Create API Key. Enter the name of the new API key in the API Key Name field and click Create:

After this, SendGrid will give you a new API key that you can use in your applications.

2. Configuring Laravel

Open the .env file, find variables with mail settings and complete them with these values:

MAIL_DRIVER=smtp MAIL_HOST=smtp.sendgrid.net MAIL_PORT=2525 MAIL_USERNAME=apikey MAIL_PASSWORD="YOUR_API_KEY" MAIL_ENCRYPTION=tls

Now, you can the use default Laravel interface to send emails.

3. Testing

For testing you can create a simple Laravel command that will send mail to your mail inbox. For example:

php artisan make:command EmailSendingTestCommand

Then, paste this code in the handle() method of the command to send mail without creating views and Mailable class:

Mail::raw("Test email text", function ($message) { $message->to("your_mail@address"); $message->subject("Test"); });

After this, you can run this command, and it will send a test email to you.

Wrapping Up

In this short article, we have explained how to use SendGrid in Laravel. As you can see, it is very simple because SendGrid uses standard SMTP protocol. In this case you can use built-in functionality, but very often there is need to work with APIs that do not have built-in support or libraries. You can read how to do it in the article How to Request to External API in Laravel.

Leave a Comment