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.
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
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');
}
}
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 !!
Now, Create route for testing send mail
Route::get('test_mail','UserController@testMail');
Now create UserController and add below code.
public function testMail()
{
$mail = 'your_mail@gmail.com';
Mail::to($mail)->send(new TestMail);
dd('Mail Send Successfully !!');
}
And after that you will get output like below screenshot.
You might also like :