Mailtrap is a Test SMTP server which we can use as a service to send email, test or share email messages to the mailbox, In a way that the real user does not get disturbed and mark the email spam. And to do that you have to configure Mailtrap, which can be done easily in just few simple steps.
configure mailtrap SMTP and send email in laravel 5.4
Steps to configure mailtrap:
1) Register to mailtrap: https://mailtrap.io/register/signup
2) Go to Inbox page: https://mailtrap.io/inboxes
3) Click on Demo Inbox link and you will see the following mailtrap smtp credentials as shown below
Now go to .env file in the root directory of your project and paste the following line:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=**************
MAIL_PASSWORD=**************
MAIL_ENCRYPTION=null
Next, run the following command in the laravel project directory:
php artisan make:mail Welcome
After running the above command Mail folder will be created under app directory if it is not present and Welcome.php file will be created under Mail folder. Replace the code with the following:
<?php namespace AppMail; use IlluminateBusQueueable; use IlluminateMailMailable; use IlluminateQueueSerializesModels; use IlluminateContractsQueueShouldQueue; class Welcome 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('emails.welcome'); } }
If you compare the above code from the original one in Welcome.php file, then you will see build function has been modified. This function will render the welcome page which has been created under resources/emails/welcome.php
Now go to your controller in which you will send the email and include the following line of code on the top:
use App\Mail\Welcome;
Above line will call the Welcome class which you just created under app/Mail/Welcome.php
Create following function in the controller to send mail:
public function sendmail(){
$user = Auth::user();
\Mail::to($user)->send(new Welcome);
return redirect()->home();
}
You can modify sendmail function according to your requirement. Here I am sending mail to respective user by reading the Auth. Use below line to send mail to the respective user.\Mail::to($user)->send(new Welcome);
Create email template under following directory: laravelProject/resources/views/emails/welcome.blade.php . You can modify welcome.blade.php file according to you:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Welcome to laravel</h1>
</body>
</html>
Ref: https://scotch.io/tutorials/ultimate-guide-on-sending-email-in-laravel
Thats all you have to do. If you have any questions please feel free to write in comment section below.