Sending emails in your Laravel application can be a challenging task. However, utilizing services such as SendGrid can simplify the process. In this blog post, we will discover how to implement SendGrid in Laravel for sending emails.
To start, you’ll need an account with SendGrid. Once that’s sorted, you can proceed with the following steps.
Step 1: Install SendGrid API Library
The SendGrid API library can be installed in your Laravel project using Composer. Run the following command in your terminal to install:
composer require sendgrid/sendgrid
Step 2: Configure .env File
After installing SendGrid, you need to configure your .env file. Configure the mail settings in your .env file as follows:
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}"
Remember to replace your_sendgrid_api_key with the actual SendGrid API Key and your_email_address with the email address you want to send emails from.
Step 3: Create Mailable
Laravel uses Mailable classes to represent each type of email sent by your application. You can generate a new mailable class using the make:mail command. Let’s create a new mailable class named TestEmail:
php artisan make:mail TestEmail
Step 4: Configure Mailable
Next, we need to configure our Mailable class. For the sake of simplicity, we’ll set up a basic email content. Open the file you just created (TestEmail.php), it should look something like this:
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; class TestEmail extends Mailable { use Queueable, SerializesModels; /** * Create a new message instance. * * @return void */ public function __construct() { // } /** * Build the message. * * @return $this */ public function build() { return $this->view('emails.test'); } }
Step 5: Send the Email
After setting up your Mailable, you can use Laravel’s Mail facade to send the email. Here’s a simple example of how to send an email:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; use App\Mail\TestEmail; class EmailController extends Controller { public function sendEmail() { Mail::to('recipient@example.com')->send(new TestEmail()); return "Email sent!"; } }
That’s it, you’ve successfully set up SendGrid with Laravel! Now you can send emails through your Laravel application with ease. Happy coding!