Laravel 10 : How to send email | Laravel Send Email Tutorial
How to Send Email in Laravel 10 Step by Step :
Step 1: Install the Laravel App
Laravel new send-email
This command will create a new project in the directory. For laravel 10 you need to have PHP 8.2 or higher version installed in your system.
Step 2: Set up Your SMTP details in the .env file. you will find that file in the root directory.
MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
Step 3: Create a Mail Class in you project
Now we will create an Email class named MailService.php. In this file we will update the mail subject and the email body.
php artisan make:mail MailService
This command will create a Mail Service file in app/mail/MailService.php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class MailService extends Mailable
{
use Queueable, SerializesModels;
public $data;
/**
* Create a new message instance.
*/
public function __construct($data)
{
//
$this->data = $data;
}
/**
* Get the message envelope.
*/
public function envelope(): Envelope
{
return new Envelope(
subject: 'Your Email Subject',
);
}
/**
* Get the message content definition.
*/
public function content(): Content
{
return new Content(
view: 'email.mailFile',
);
}
/**
* Get the attachments for the message.
*
* @return array
*/
public function attachments(): array
{
return [];
}
}
Step 4:
Create a controller for sending mail:
Now we will create a controller with the below command for sending mails.
php artisan make:controller EmailController
Code of Email Controller file below:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\MailService;
class EmailController extends Controller
{
//
public function send()
{
$data = [
'name'=> "The Infinite Insights",
'content'=>'This is a test Content..'
];
Mail::to('yourEmail@gmail.com')->send(new MailService($data));
echo "mail Send success";
}
}
Make Sure to change the Email address above.
Step 5: Create Route For Sending Email:
Now we will create a Route for Sending email code as follows:
Route::get('send-mail', [EMailController::class, 'send']);
Put this code in the routes/web.php file.
<!DOCTYPE html>
<html>
<head>
<title>The Infinite Insights</title>
</head>
<body>
<h1>Hi, There {{$data['name']}}</h1>
<p>{{$data['content']}}</p>
</body>
</html>
Step 7: Test The Email service:
Run Laravel App by php artisan serve and then go to http://localhost:8000/send-mail and the mail will be sent . If you have any query related to this feel free to mail me at info@infiniteinsights.com.