How To Send Email In Laravel 9

Spread the love

Hello Guys,

In this tutorial, we will explore how to efficiently Send Email in Laravel 9. This comprehensive guide will walk you through the entire process of sending emails using Laravel 9 SMTP, providing you with a step-by-step Laravel 9 send mail example. Additionally, we’ll delve into a practical Laravel 9 SMTP send mail sample to reinforce your understanding.

Laravel 9 enhances your email-sending capabilities by offering a built-in mail setup feature. With Laravel 9, you can send emails using various drivers, such as SMTP, Mailgun, Postmark, and Amazon SES. To select your preferred driver, it’s crucial to configure it in your env file.

For a detailed and insightful tutorial on sending emails with Laravel 9, check out the following article. This resource covers everything from creating Blade file templates to designing dynamic mail layouts. So, let’s embark on this step-by-step journey to empower you to Send Email in Laravel 9 according to your specific requirements.

Send Email in Laravel 9 Example:

Step 1: Install Laravel 9

While it’s not mandatory, you’re welcome to proceed and execute the following command if you haven’t yet established your Laravel application:

Also Read: How To Create Repeater Field Using Bootstrap

composer create-project laravel/laravel example-app

Step 2: Make Configuration

In the initial step of setting up Laravel 9, it’s crucial to include the email sending configuration. This configuration should encompass essential parameters such as the mail driver, mail host, mail port, mail username, and mail password. These settings are vital for Laravel 9 to effectively send emails. Below, we provide a simple guide on how to incorporate these configurations:

Ensure you’ve configured the necessary email settings, including the mail driver, mail host, mail port, mail username, and mail password, in the first step of Laravel 9 setup. These settings play a pivotal role in facilitating seamless email communication. Here’s a step-by-step guide on how to integrate them.

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=itcodestuff@gmail.com
MAIL_PASSWORD=itcodestuff@123
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=itcodestuff@gmail.com
MAIL_FROM_NAME="${APP_NAME}"

Step 3: Create Mail Class

To facilitate email sending, we’ll be crafting the YourDemoMail class during this phase. Within this context, we will be responsible for authoring the code that will be invoked by the user object within the view. Let’s proceed by running the command provided below.

Also Read: How to use laravel cookies – Get, Set, Delete with example

php artisan make:mail YourDemoMail

Now, it’s time to make some changes to the code in YourDemoMail.php file. Follow the steps below:

<?php
  
namespace App\Mail;
  
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
  
class YourDemoMail extends Mailable
{
    use Queueable, SerializesModels;
  
    public $mailData;
  
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($mailData)
    {
        $this->mailData = $mailData;
    }
  
    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->subject('Mail from itcodestuff.com')
                    ->view('emails.yourDemoMail');
    }
}

In this tutorial, we’ll guide you through the process of creating a MailController featuring an index() method for sending emails to a specified recipient. To begin, we’ll start by crafting a controller by executing the prescribed command and subsequently modifying the code within it. This step-by-step guide will help you seamlessly integrate email functionality into your project.

php artisan make:controller MailController

Next, make sure to modify the code within the MailController file for the required updates.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Mail;
use App\Mail\YourDemoMail;
  
class MailController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $mailData = [
            'title' => 'Mail from itcodestuff.com',
            'body' => 'This is for testing email using smtp.'
        ];
         
        Mail::to('yourEmail@gmail.com')->send(new YourDemoMail($mailData));
           
        dd("Email is sent successfully.");
    }
}

Step 5: Create Routes

In this crucial step, we will guide you on how to establish routes for sending emails effectively. To get started, please access your “routes/web.php” file and insert the provided route below. This action will optimize your email sending process.

Also Read: How To Generate PDF Files using DomPDF In Laravel 9

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\MailController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('send-mail', [MailController::class, 'index']);

Step 6: Create Blade View

In this phase, we will craft the email content and generate a blade view file. Currently, our primary task is to generate placeholder text. To accomplish this, please navigate to the “emails” directory and establish the subsequent files.

<!DOCTYPE html>
<html>
<head>
    <title>itcodestuff.com</title>
</head>
<body>
    <h1>{{ $mailData['title'] }}</h1>
    <p>{{ $mailData['body'] }}</p>
  
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
     
    <p>Thank you</p>
</body>
</html>

Run Laravel App:

After successfully following all the required steps, it’s time to execute the following command and press Enter to initiate the Laravel application launch:

php artisan serve

To access the app’s output, simply input the given URL into your web browser.

http://localhost:8000/send-mail

Embrace the elite realm of Laravel insights – your compass to the best Laravel blog awaits.

Leave a Comment