Sending emails in Laravel 12 using Gmail SMTP is easy and efficient. In this guide, I’ll show you how to set up your Gmail SMTP server, configure Laravel’s mail settings, and send emails using Laravel’s built-in Mailable class. Follow along with the step-by-step instructions and example code.
Laravel 12 Send Emails Using Gmail SMTP
If you have not installed Laravel 12 yet, you can install it using the following command:
laravel new laravel12-email
Open your Laravel project and update the .env file with your Gmail SMTP settings:
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=your-app-password
MAIL_ENCRYPTION=tls
[email protected]
MAIL_FROM_NAME="Your Name"
Important: Gmail now requires an "App Password" instead of your regular password. Generate one from your Google Account’s security settings.
Run the command to generate a Mailable class:
php artisan make:mail TestMail
Now, open app/Mail/TestMail.php and modify it:
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 TestMail extends Mailable
{
use Queueable, SerializesModels;
public $details;
public function __construct($details)
{
$this->details = $details;
}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Test Email from Laravel 12',
);
}
/**
* Get the message content definition.
*/
public function content(): Content
{
return new Content(
view: 'emails.testMail'
);
}
/**
* Get the attachments for the message.
*
* @return array
*/
public function attachments(): array
{
return [];
}
}
Create a new view file at resources/views/emails/testMail.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel Mail</title>
</head>
<body>
<h1>{{ $details['title'] }}</h1>
<p>{{ $details['body'] }}</p>
</body>
</html>
Run this command:
php artisan make:controller MailController
Modify app/Http/Controllers/MailController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\TestMail;
class MailController extends Controller
{
public function sendEmail()
{
$details = [
'title' => 'Laravel 12 Email Test',
'body' => 'This is a test email sent using Gmail SMTP in Laravel 12.'
];
Mail::to('[email protected]')->send(new TestMail($details));
return 'Email sent successfully!';
}
}
Modify routes/web.php:
use App\Http\Controllers\MailController;
Route::get('/send-email', [MailController::class, 'sendEmail']);
Start the Laravel development server:
php artisan serve
You might also like: