Send Email In Laravel

    In this article, we will see how to send emails in laravel 6 and laravel 7. In this post, we will show how to send emails using SMTP in laravel. email is a very basic and important feature in the web development field and it is necessary for all clients.

    Sending email doesn't have to be complicated. Laravel provides a clean, simple email API powered by the popular Symfony Mailer component. Laravel's email services may be configured via your application's config/mail.php configuration file.

    So, let's see how to send mail in laravel 6/7.

Laravel 6/7 Send Mail Example

Step 1: Setup Mail Configuration
Step 2: Create Mail
Step 3: Create Blade File
Step 4: Create Route
Step 5: Create Controller
Step 1: Setup Mail Configuration

    First of all, we need to set the configuration in the .env file for sending mail, here we use SMTP. So, set the configuration as 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 provides an inbuilt mail class for sending mail. So, we will create testmail class for the same.

php artisan make:mail TestMail

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

    Add the below code for viewing.

<?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');
    }
}
Step 3: Create Blade File

    Now, I have created a Test_mail.blade.php file and we will add some text dummy text for email test purposes.

    view/mail/Test_mail.blade.php

Hi <br/>
This is Test Mail From Websolutionstuff. <br />
Thank you !!
Step 4: Create Route

    Now, create a route for testing send mail.

Route::get('test_mail','[email protected]');
Step 5: Create Controller

     Now, we will create UserController and add the below code.

public function testMail()
{
	$mail = 'websolutionstuff @gmail.com';
	Mail::to($mail)->send(new TestMail);

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

    And after that, you get output like the below screen print.

    send_email_in_laravel

    You might also like:

Bình luận
Vui lòng đăng nhập để bình luận
Một số bài viết liên quan