PHP Laravel 5.6 - Send Email using Mail Example

March 20, 2018 | Category : Laravel 5.6 Laravel PHP

in this tutorial, we are going to explore a Mail in Laravel 5.6 application. I will provide a simple example of how to send email using smtp driver in Laravel 5.6 application. you can simply use sendmail, mailgun, mandrill, ses, sparkpost, log, array as a driver in laravel 5.6 application.

Here I will give you an example using Mail facade. we will create Mail Class and send an email. so here in this example, i create HDTutoMail mail class and I am using that class when I require sending an email.

Before to create this mail class we need to set the configuration of email. If you want to send email using Gmail configuration then you can follow this link: How to send email using Gmail in PHP Laravel 5?.

So, let's follow bellow few step to send email.

Step 1: Set Configuration

first of all we need to create configuration in .env file. so let's open file and set configuration.

.env

MAIL_DRIVER=smtp

MAIL_HOST=smtp.gmail.com

MAIL_PORT=587

MAIL_USERNAME=addYourEmail

MAIL_PASSWORD=AddYourEmailPassword

MAIL_ENCRYPTION=tls

Step 2: Create Mail Class

In this step we will create mail class HDTutoMail 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 HDTutoMail

app/Mail/HDTutoMail.php

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;

use Illuminate\Mail\Mailable;

use Illuminate\Queue\SerializesModels;

use Illuminate\Contracts\Queue\ShouldQueue;

use App\User;

class HDTutoMail extends Mailable

{

use Queueable, SerializesModels;

/**

* The user instance.

*

* @var Order

*/

public $user;

/**

* Create a new message instance.

*

* @return void

*/

public function __construct(User $user)

{

$this->user = $user;

}

/**

* Build the message.

*

* @return $this

*/

public function build()

{

return $this->view('emails.HDTutoMail');

}

}

Step 3: Create 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/HDTutoMail.blade.php

<!DOCTYPE html>

<html>

<head>

<title>HDTutoMail</title>

</head>

<body>

<h1>Mail from HDTuto.com</h1>

<p>Thank you, {{ $user->name }}</p>

</body>

</html>

Step 4: Create Route

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

routes/web.php

Route::get('HDTutoMail', function () {

$user = \App\User::find(1);

Mail::to($user->email)->send(new \App\Mail\HDTutoMail($user));

dd("Email is Send.");

});

Now you can run and check example.

I hope you found your best solution.