Laravel 8.x Send Mail with SMTP Server Example

Hello Devs in this tutorial i am going to discuss from scratch that how we can send email in Laravel 8.x. In this example, i will discuss laravel 8 send email example. let’s learn about laravel 8 send mail example. This post will give you simple example of send email in laravel 8 using smtp server. let’s discuss about laravel 8 send mail smtp example from scratch.

You know that Laravel 8.x provide mail class to send email. you can use several drivers for sending email in laravel 8 what ever you want from them. you can use smtp, Mailgun, Postmark, Amazon SES, and sendmail services in Laravel. We have to configure on env file what driver you want to use.

 

Step 1: Make Configuration

In this step, you need 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 below example.

.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: Make 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 tutspack.com')
                    ->view('emails.myTestMail');
    }
}

 

Read also : Laravel Set Dynamic Page Title Example

 

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

 

Step 4: Create 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 () {
   
    $details = [
        'title' => 'Mail from tutspack.com',
        '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 all are set to go. You can check it now.