How to Send Mail using Sendgrid API in Laravel 10?

Spread the love

Hello Guys,

Sending emails using Sendgrid API in Laravel 10 is a breeze. Discover how to send and track your emails with incredible speed and precision. The tracking feature of Sendgrid API is a game-changer, enabling you to monitor email opens and clicks with ease. In this post, we’ll walk you through the process of setting up Sendgrid in your Laravel 10 application, so you can effortlessly send emails. Plus, we’ll show you how to send basic emails through the Sendgrid website.

By harnessing Sendgrid for your email communication, you can significantly reduce loading times and receive emails promptly.

First, we’ll guide you through the process of configuring your email settings. We’ll start by adding Gmail account configuration.

Simply open your .env file and enter the following code:

Also Read: How to Generate SITEMAP in laravel 10

.env
MAIL_DRIVER=smtp
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=sendgridusername
MAIL_PASSWORD=sendgridpassword

To set up SendGrid API configuration, you’ll want to start by creating a new account on sendgrid.com if you haven’t done so already. Once you’re registered, generate a unique username and password for your SendGrid account.

With your SendGrid account ready, you can proceed to set up a test email sending route as we prepare to send a test email.

app/Http/routes.php
Route::get('send-mail', 'SendMailController@sendmail');

Now, add the sendmail() function to the SendMailController.php file as follows:

app/Http/Controllers/SendMailController.php
public function sendmail()
{
    $user = User::find(1)->toArray();
    Mail::send('emails.mailEvent', $user, function($message) use ($user) {
        $message->to($user->email);
        $message->subject('Sendgrid Testing Mail');
    });
    dd('Mail Send Successfully!');
}

Let’s build the userMail.blade.php file in the emials folder to finish creating the email template file for sending mail.

Also Read: How to Get All Routes in Laravel 10

resources/views/emails/userMail.blade.php
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>sendgrid testing email - itcodestuff.com</title>
    </head>
    <body>
        <div>
            <h1>Hi, sendgrid testing email from itcodestuff.com</h1>
        </div>
    </body>
</html>

Now, Enter the provided URL into your web browser to view the app’s output.

Also Read: How to Create a Custom Error Page in Laravel 10?

http://127.0.0.1:8000/send-mail

Dive into our collection of Laravel blogs – your go-to source for expert insights.

Leave a Comment