How to send Emails using SMTP in Laravel 9 from localhost and live server

Cyberac1d
0

 

In this tutorial, we will send email in Laravel 9 using SMTP with step by step guide. This method will work with both live and localhost server, because we are using SMTP mail server.

Sending emails is the core functionality of any web application, Laravel 9 also comes with mail drivers to send emails. There are many ways we can send our emails through services like SMTP, Amazon SES, sendmail, Postmark,SendinBlue,Mailjet and Mailgun.

Let's get started with our tutorial:

    Follow the below simple steps to send email in Laravel 9 using SMTP:

    1. Install Laravel 9 & Configure SMTP Credentials in env file
    2. Create a Mail Class
    3. Create a Mail Controller
    4. Create an Email Directory and Blade View file template
    5. Add an Email Route 
    6. Run and Test our Application


    Step 1: Install Laravel 9 & Configure SMTP Credentials in .env file

    First of all, we will install a fresh code of Laravel 9 Framework by running the below command in command prompt or terminal. 

    You can skip this step if you already have the code setup.

    composer create-project --prefer-dist laravel/laravel sendEmail

    Once Laravel is installed successfully then configure the .env file with the following SMTP credentials which will be used by Laravel to send email.

    For this tutorial we are using Gmail SMTP configuration, you can use any SMTP credentials, make the changes in your .env file as below.

    MAIL_MAILER=smtp
    MAIL_HOST=smtp.gmail.com
    MAIL_PORT=465
    MAIL_USERNAME=your_email@gmail.com
    MAIL_PASSWORD=your_password
    MAIL_ENCRYPTION=ssl
    MAIL_FROM_ADDRESS=your_email@gmail.com
    MAIL_FROM_NAME="${APP_NAME}"

    Note: If you are using Gmail to send your email so you will need to enable Less secure app access from your Gmail account setting from following link https://myaccount.google.com/u/1/lesssecureapps .

    2. Create a Mail Class

    In this step, we will create a Mail class with name TestMail for sending our test emails. This will call the view of test email.

    Run the below command to create a Mail class in Laravel project.

    php artisan make:mail TestMail

    Now update the code on app/Mail/SendMail.php file as below.

    <?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;
    
        public $mailData;
    
        /**
         * Create a new message instance.
         *
         * @return void
         */
        public function __construct($mailData)
        {
            $this->mailData = $mailData;
        }
    
        /**
         * Build the message.
         *
         * @return $this
         */
        public function build()
        {
            return $this->subject('Email From https://www.appwebtut.com/')
                        ->view('emails.testMailTemplate');
        }
    }

    3. Create a Mail Controller

    In this step, I will create a controller with name EmailController with an index() method that will send an email to your desired email address.

    Run the below command to create a mail controller.

    php artisan make:controller EmailController

    Now update the app/Http/Controllers/EmailController.php code as below.

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use Mail;
    use App\Mail\TestMail;
    
    class EmailController extends Controller
    {
        public function index()
        {
            $mailData = [
                'title' => 'Test Email From appwebtut.com',
                'body' => 'This is the body of test email.'
            ];
    
            Mail::to('your_email@gmail.com')->send(new TestMail($mailData));
    
            dd('Success! Email has been sent successfully.');
        }
    }

    4. Create an Email Directory and Blade View file template

    In this step, we will create an email directory in resources/views directory and then create a new email blade template view file with name testMailTemplate.blade.php and paste the below code in it here resources/views/emails/testMailTemplate.blade.php.

    <!DOCTYPE html>
    <html>
    <head>
        <title>AppWebTut.com</title>
    </head> <body> <h1>{{ $mailData['title'] }}</h1> <p>{{ $mailData['body'] }}</p>
    <center>Thankyou!!</center></body> </html>

    5. Add a Send Email Route in web.php

    In this step, we will create a web route, add the below code in routes/web.php file to register the route that will send test email.

    <?php
    
    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\EmailController;
    
    
    /*
    |--------------------------------------------------------------------------
    | Web Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register web routes for your application. These
    | routes are loaded by the RouteServiceProvider within a group which
    | contains the "web" middleware group. Now create something great!
    |
    */
    Route::get('/send-email', [EmailController::class, 'index']);

    6. Run and Testing the Application

    Now, we have completed all required steps to send an email from Laravel 9 using Gmail SMTP server. Now we can start the development server and test the email.

    Run the following command to run the development server or open your localhost url in the browser.

    php artisan serve

    Now go to the browser and hit the below URL to send email from Laravel 9 using SMTP.

    http://localhost:8000/send-emailORhttp://localhost/<laravelProjectName>/public/send-email<laravelProjectName> replace this with your directory name

    You will get an email like below in your inbox.




     


    Post a Comment

    0Comments

    Thanks for sharing your feedback! It helps us grow.

    Post a Comment (0)

    Contact form