Laravel 9 Mail Tutorial | How to Send Email

Laravel 9 Mail Tutorial | How to Send Email
Laravel 9 Mail Tutorial | How to Send Email

In this tutorial, you are going to learn how to work with Laravel mail and send emails. We are going to use Mailtrap for this demo project. so you need to create an account to mailtrap.io. This post will give you an easy example of sending an email to Laravel 9 SMTP. You can use several drivers to send emails to Laravel 9. you can use SMTP, Mailgun, Postmark, Amazon SES, and Sendmail you must configure in the env file which driver you want to use. So let’s see a step-by-step guide and send an email to your requirement.

Steps to send emails with Laravel 9 Mail

1 Step one ENV Configuration

In the first step, you need to add the email configuration and email driver, mail host, mail port, email username, and email password so that laravel 9 will use that email sender information. So add the following if you are using mailtrap.io.

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your username
MAIL_PASSWORD=your password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="[email protected]"
MAIL_FROM_NAME="${APP_NAME}"

2 Step Two Create Mail

In this step, we will create a mail class FirstMail for sending emails. Here we will write code for which view will call and the object of the user. So let’s run the below command.

php artisan make:mail FirstMail
<?php
  
namespace App\Mail;
  
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
  
class First extends Mailable
{
    use Queueable, SerializesModels;
  
    public $name;
  
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($name)
    {
        $this->name = $name;
    }
  
    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->subject('Mail from laraveller.com')
                    ->view('mails.first-mail');
    }
}

3 Step Three Create Blade View for Mail

In this step, we will create a blade view file and write the email that we want to send.

resources/views/mails/first-mail.blade.php
<h1>My first mail to mailtrap.io send from {{ $name }}</h1>

4 Step Four Create The Route

So let’s create the below web route for testing and send the email.

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

Route::get('/send-mail', function () {

    $name = "Laraveller";
     Mail::to('[email protected]')->send(new FirstMail($name));
});

Now you can run and check examples.

It will send you an email, let’s see.

Watch Full Video Tutorial on how to send emails with Laravel.

Suggested Laravel tutorials for beginners

Leave a Reply

Your email address will not be published.