Laravel Mail | Laravel Send Email Tutorial | How to send Mail in Laravel

Sending email doesn't have to be complicated. Laravel provides a clean, simple email API powered by the popular Symfony Mailer component. Laravel and Symfony Mailer provide drivers for sending email via SMTP

In this tutorial, i will give you step by step instruction to send email in laravel 8. you can create blade file design and also with dynamic information for mail layout. so let's see step by step guide and send email to your requirement.

Step 1: Make Mail Configuration

In first step, you have to add send mail configuration with mail driver, mail host, mail port, mail username, mail password so laravel 8 will use those sender details on email. So you can simply add as like following.

.env


MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=mygoogle@gmail.com
MAIL_PASSWORD=rrnnucvnqlbsl
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=mygoogle@gmail.com
MAIL_FROM_NAME="${APP_NAME}"

Step 2: Create Mail

In this step we will create mail class MyTestMail for email sending. Here we will write code for which view will call and object of user. So let's run bellow command.


php artisan make:mail MyTestMail

app/Mail/MyTestMail.php


namespace App\Mail;
  
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
  
class MyTestMail extends Mailable
{
    use Queueable, SerializesModels;
  
    public $details;
  
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($details)
    {
        $this->details = $details;
    }
  
    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->subject('Mail from appetenza.in')
                    ->view('emails.myTestMail');
    }
}

Step 3: Create Blade View

In this step, we will create blade view file and write email that we want to send. now we just write some dummy text. create bellow files on "emails" folder.

resources/views/emails/myTestMail.blade.php


<h1>{{ $details['title'] }}</h1>
<p>{{ $details['body'] }}</p>
<p>Thank you</p>

Step 4: Add Route

Now at last we will create "MyTestMail" for sending our test email. so let's create bellow web route for testing send email.

routes/web.php


Route::get('send-mail', function () {a  
    $details = [
        'title' => 'Mail from appetenza.in',
        'body' => 'This is for testing email using smtp'
    ];
    \Mail::to('your_receiver_email@gmail.com')->send(new \App\Mail\MyTestMail($details)); 
    dd("Email is Sent.");
});

Now you can run and check. It will send you email, let' see.

Run Project:


php artisan serve

Open Link:

http://localhost:8000/send-mail

I believe it can help you...

Comments

Abhi

very helpful

Leave a Reply