Laravel6 - How to send mail in laravel

  5 months ago     Views:  339  
Site Admin
4 Follows


Laravel has so many builtin features like authentication, facades, routes. That is the reason why Laravel has become so pupular in web development. One of the main feature Laravel provides is that simple and clean mail functionality. Laravel uses popular SwiftMailer library to send mail.

In this tutorial, we will setup new create new Laravel 6 Project and will send email from localhost.

Setup Laravel application

First, we will create new Laravel 6 project. To do so, open Terminal and run the following command. It will create sendmail project.

composer create-project laravel/laravel sendmail --prefer-dist

Now go to your project directory and open .env file and set bellow configurations. We are using Google to send mail.

In Google account, check that 2-Step Verification is set to off. To do, Go to My account > Security and turn off 2-Step Verification.

You also need to enable Less secure app access in the Security tab.

If you don't want to disable 2-Step Verification, then you can generate App passwords and use this password in .env configuration.

It will make possible to send mail from your application without authentication. Now put mail configurations in your .env file

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_FROM_ADDRESS=username@gmail.com
MAIL_FROM_NAME='Username'
MAIL_USERNAME=username@gmail.com
MAIL_PASSWORD=*************
MAIL_ENCRYPTION=tls

Route and Controller

Now we will create route which will trigger mail to send controller.

In this routes/web.php file, we have create bellow route.

<?php

Route::get('send-mail', 'HomeController@sendMail');

So when we will hit 'send-mail' URL in browser, it will hit sendMail() method in HomeController.

So let's create HomeController by using this artisan command.

php artisan make:controller HomeController

Now open this controller at App/Http/Controllers/HomeController.php and add new classmethod sendMail() in the controller.

<?php

namespace App\Http\Controllers;

use Mail;
use App\Mail\SendMail;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Send email.
     *
     * @return void
     */
    public function sendMail()
    {
        $details['to'] = 'receivermail@gmail.com';
        $details['name'] = 'Receiver Name';
        $details['subject'] = 'Hello HacktheStuff';
        $details['message'] = 'Here goes all message body.';

        Mail::to($details['to'])
                ->send(new SendMail($details));
    }
}

In the Mail, we will pass to() method with receiver email address and send() method will send email with object of Mailable class. You can also chain cc() and bcc() method before send method to send mail more than one User.

Mail::to($details['to'])
    ->cc($new_user_email)
    ->bcc($also_new_user_email)
    ->send(new SendMail($details));

Mail Facade.

Now go to Terminal and create Mail facade with following command:

php artisan make:mail SendMail

It will create new PHP file at Mail/SendMail.php with same class name. Open file and change build() function which will return view file. subject() method will display subject in the send mail. In the with method, we are passing $details variable, which is available in view file.

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendMail 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->view('email.send_mail')
                ->subject($this->details['subject'])
                ->with('details', $this->details);
    }
}

View Mail content.

Now go through directory resources/views and create new blade file email/send_mail.blade.php. This file will be sent to Mail. Open this file and create html view as you want to send. We will here put simple HTML view:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Welcome Email</title>
    <link rel="stylesheet" href="">
</head>
<body>
    <h2 style="text-align: center;">HacktheStuff</h2>
    <p>Hello!{!! $details['name'] !!}</p>
    <br>
    <p>{!! $details['message'] !!}</p>
</body>
</html>

Start the server and send mail

Now you have completed code so only need is to start server. Go to the Terminal window and start server.

php artisan serve

In your browser run the bellow url:

http://localhost:8000/send-mail

If you didn't get any errors then you get response that "Email sent successfully".

Conclusion

In this way, you can easily send email dynamically from your Laravel website. In the next article we will discuss about how to send email with Laravel Queue and Job, which helps to send mail in bulk.

If you need help or have suggestion, do leave a comment below.


Was this article helpful?

1 out of 1 person found this article helpful.

Leave a comment

OR

No Comments