Laravel 7 Email Sending using mailtrap.

mailtrap_login

In this tutorial, I will teach how to sending mail in laravel 7 and how to mail used in systems so it will help in big projects.


Step 1: Open the mailtrap.io

You have open the mailtrap.io in your browser and if you already create an account then click on the login button otherwise signup button click and create a new account.


Step 2: Email Configuration.

After login or signup in mailtrap.io, you have got information about credentials.

You have to put these credentials into your .env file.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME= //username from your mailtrap credentials.
MAIL_PASSWORD= //password from your mailtrap credentials.
MAIL_ENCRYPTION=null

Step 3: Create a Mail sending class.

So open your terminal OR command prompt and run bellow command:

php artisan make:mail NewMail

In this step, we have to find App\Mail\NewMail.php and put the below code.

<?php
  
namespace App\Mail;
   
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
  
class NewMail extends Mailable{
    use Queueable, SerializesModels;
    public $user_info;

    public function __construct($user_info){
        $this->user_info = $user_info;
    }
    public function build(){
        return $this->subject('This is Testing Mail')
                    ->view('email.newMail');
    }
}

Step 4: Create Blade View

In this step, we have to find resources/views and create a new folder name email & create a new file newMail.blade.php and put the below code.

<!DOCTYPE html>
<html>
<head>
    <title>This Email generated by Oakml.com</title>
</head>
<body>
    <h1>{{ $user_info['name'] }}</h1>
    <p>{{ $user_info['info'] }}</p>
    <p>Thank you</p>
</body>
</html>

Step 5: Create a Route

You can directly create a function in the web.php or you can create a function in the controller file so open your file and put the below code

Route::get('email-send', function () {
    $user_info = [
        'name' => 'Dhaval Shah',
        'info' => 'Laravel Developer'
    ];
    \Mail::to('yourmail-id@gmail.com')->send(new \App\Mail\NewMail($user_info));
    dd("Email was send Successfully.");
});

Now Open your browser and put the below link.

http://127.0.0.1:8000/email-send

I hope it will help you!

About Dhaval Shah

My name is Dhaval Shah. I'm a Laravel developer. I live in India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Java-script, JQuery, Laravel, WordPress, and Bootstrap.
Follow me on Github / Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!