How to send mail in laravel 9

How to send mail in laravel 9

Send Email in Laravel 9

ยท

2 min read

Send MAIL In Laravel 9

Today I am going to explain how you can send MAIL using SMTP in Laravel 9.

Laravel UI Installation.

I have installed the laravel Now we will open the code in Editor.

Step - 1

Open .env file and change the MAIL Provider SMTP Details

MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

You can use MailTrap to generate basic SMTP Details and test your email feature.

Step - 2

Now Generate the email class by running the command

php artisan make:mail TestEmail

this command will generate the file in app/Mail/TestEmail.php

Open the file and update the code below.

<?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;

    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('Test Email')->view('email.test');
    }
}

Step - 3

Now Let's create a blade view file, for that let's create email folder first inside resources/view.

Now create a test.blade.php file inside email folder and paste the code below.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Test Email</title>
</head>
<body>
    <h1>Test EMAIL</h1>
    <p>Name: {{ $mailData['name'] }}</p>
    <p>DOB: {{ $mailData['dob'] }}</p>
</body>
</html>

Step - 4

Now create a route to send email put the code below to routes/web.php


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

Route::get('send-email', function(){
    $mailData = [
        "name" => "Test NAME",
        "dob" => "12/12/1990"
    ];

    Mail::to("hello@example.com")->send(new TestEmail($mailData));

    dd("Mail Sent Successfully!");
});

Now visit to /send-email in the browser it should send the email to the inbox.

The Email Will look like.

EMAIl INBOX

The complete Tutorial is below in the video.

If you face any issue while installing, please comment your query.

Thank You for Reading

Reach Out To me. Twitter Instagram TechToolIndia YouTube Channel

Did you find this article valuable?

Support Shani Singh by becoming a sponsor. Any amount is appreciated!

ย