How To Send Mail In Laravel

Laravel email services configured via the mail configuration file.

Syntax :

Mail::send([‘text’=>’text.view’], $data, $callback);

Example :

You need to configure your gmail account in Laravel environment .env file.

changing the .env parameters as following.

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your_gmail_id
MAIL_PASSWORD=your_gmail_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"

Create a controller file MailController.php and save it in the following path app/Http/Controllers/MailController.php.

php artisan make:controller MailController

After typing the Composer command in the command prompt as shown in the following screenshot.

MailController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mail;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class MailController extends Controller {
   
   public function html_email() {
      $data = array('name'=>"John");
      Mail::send('mail', $data, function($message) {
         $message->to('abc@gmail.com', 'Howtowebcode')->subject
            ('Laravel Testing Mail');
         $message->from('yourgmail@gmail.com','John');
      });
      echo "Email send suuccessfully....!";
   }
}
?>

Create a view file crud.blade.php and save the below code it in resources/views/mail.blade.php.

<h1>Hi, {{ $name }}</h1>
l<p>Sending Mail from Laravel.</p>

Let us execute this example by the following URL in the browser. This URL may be different based on your website.

http://localhost/laravel_8/sendhtmlemail