How To Send Email In Laravel Example

In this tutorial I will give you example of how to send email in laravel 6/7/8, in this post we will show how to send email using smtp in laravel, email is very basic and most important feature in web development field and it is neccesory for all client. also we are see example of send mail in laravel using mailtrap account.

Laravel provide mail class to send email. you can use several drivers for sending email in laravel. you can use Mailgun, Postmark, Mailtrap, SMTP, Amazon SES. Just you have to configure on config/mail.php or .env file as per your requirements.

So, let's start sending mail example in laravel 6/7/8 or send mail in laravel using mailtrap.

Step 1 - Configuration in .env file
Step 2 - Create mail using artisan command
Step 3 - Create blade file
Step 4 - Create route
Step 5 - Create controller

 

Step 1 : Set Configuration

First of all we need to set configuration in .env file for sending mail, here we are using smtp mailtrape. So, set according port as define below.

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=TLS

 

 

Step 2 : Create Mail Using Artisan Command

Laravel provide inbuilt mail class for sending mail. So, we need to create testmail class for same,

php artisan make:mail TestMail

Now you can found file in this location app/Mail/TestMail.php

After creating file add below code for view.

<?php

namespace App\Mail;

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

class TestMail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('mail.test_mail_example');
    }
}

 

Step 3 : Create Blade File

Now, I have created test_mail_example.blade.php file.

In this path view/mail/test_mail_example.blade.php, we need to add some dummy text for email.

Hi <br/>
This is Test Mail From Techsolutionstuff.<br />
Thank you !!

 

 

Step 4 : Create Route

Now, Create route for testing send mail

Route::get('test_mail','[email protected]');

 

Step 5 : Create Controller

 Now create UserController and add below code.

public function testMail()
{
	$mail = '[email protected]';
	Mail::to($mail)->send(new TestMail);

	dd('Mail Send Successfully !!');
}

 

And after that you will get output like below screenshot.

laravel_send_mail_using_mailtrap

 


You might also like :

FEATURE POSTS