How to use SendGrid to send email in Laravel

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

When building web applications, you will often need to send emails. Laravel provides a clean, simple API over the popular SwiftMailer library, but it’s also possible to use other email delivery services like SendGrid. In this tutorial, we’ll explore how to integrate SendGrid into a Laravel application to send emails. We will go through the installation of necessary packages, setting up SendGrid with Laravel, and cover various methods of sending emails using this service.

Setting up SendGrid

First, you need to sign up for a SendGrid account. Once you have your account, create an API key with full access to “Mail Send” functionalities. Keep your API key safe as it will be used in your Laravel application to authorize email sending.

Installing SendGrid dependencies in Laravel

Laravel uses the SwiftMailer library, but you can add SendGrid as a custom mail driver. First, install the SendGrid PHP library through Composer:

composer require sendgrid/sendgrid

After the library is installed, the next step is to set the mail driver configuration. Open .env file and update the mail settings:

MAIL_MAILER=smtp
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=apikey
MAIL_PASSWORD=your-sendgrid-api-key
MAIL_ENCRYPTION=tls
[email protected]
MAIL_FROM_NAME="Example App"

Sending Basic Emails

To send a simple text email, you can use the Laravel Mail facade. Here is a basic example of sending an email using a Mailable class:

use Illuminate\Support\Facades\Mail;
use App\Mail\WelcomeEmail;

Mail::to('[email protected]')->send(new WelcomeEmail());

Here is what the WelcomeEmail Mailable class might look like:

namespace App\Mail;

use Illuminate\Mail\Mailable;

class WelcomeEmail extends Mailable
{
    public function build()
    {
        return $this->subject('Welcome to Our Application')->view('emails.welcome');
    }
}

In your resources/views/emails/welcome.blade.php you can define your HTML email template.

Advanced Usage: Sending Emails with Attachments

If you want to send attachments along with your emails, it’s just as straightforward. Update your Mailable class to include a call to the attach method:

public function build()
{
    return $this->subject('Subject Here')->view('emails.your-view')->attach('/path/to/file');

Sending Emails Using SendGrid’s Web API

In some cases, you may prefer to use SendGrid’s Web API instead of SMTP protocol. First, you need to install the Guzzle HTTP library that Laravel uses under the hood for its HTTP client:

composer require guzzlehttp/guzzle

Then, you can send an email like this:

use Illuminate\Support\Facades\Http;

$response = Http::withHeaders([
    'Authorization' => 'Bearer Your-SendGrid-API-Key',
    'Content-Type' => 'application/json'
])->post('https://api.sendgrid.com/v3/mail/send', [
    'personalizations' => [[
        'to' => [['email' => '[email protected]']],
        'subject' => 'Hello World from the SendGrid API!'
    ]],
    'from' => ['email' => '[email protected]'],
    'content' => [['type' => 'text/plain', 'value' => 'Hello, world!']]
]);

if ($response->successful()) {
    echo 'Email sent successfully.';
} else {
    echo 'Failed to send email - '. $response->body();
}

Conclusion

In this tutorial, you have learned how to use SendGrid to send emails in a Laravel application. By following these steps, you can implement an efficient email delivery service into your Laravel project that is not only powerful but also developer-friendly. The opportunities are vast with both Laravel and SendGrid, providing you the tools needed to create complex email functionality with minimal effort.