Install Laravel 12 App
Run below this command
composer create-project laravel/laravel example-app
Create gmail app password
Login gmail account and click on manage your google account
Click on security tab and search app password
Create app name
Copy your app password
Setup mysql database and SMTP
update .env file
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel12app //database name
DB_USERNAME=root
DB_PASSWORD=
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=yourGmailAccountId
MAIL_PASSWORD=yourCreatedAppPassword
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=mygoogle@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
create route
routes/web.php like as below code
<?php
use App\Http\Controllers\MailController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::controller(MailController::class)->group(function () {
Route::get('/send-email', 'sendEmail')->name('sendEmail');
});
create mail file
Run below this command
php artisan make:mail SendEmail
app\Http\Mail\SendEMail.php like as below code
<?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 SendEmail extends Mailable
{
use Queueable, SerializesModels;
public $variable;
/**
* Create a new message instance.
*/
public function __construct($variable)
{
$this->variable = $variable;
}
/**
* Get the message envelope.
*/
public function envelope(): Envelope
{
return new Envelope(
subject: 'Laravel 12 email test',
);
}
/**
* Get the message content definition.
*/
public function content(): Content
{
return new Content(
view: 'email.email-template',
);
}
/**
* Get the attachments for the message.
*
* @return array<int, \Illuminate\Mail\Mailables\Attachment>
*/
public function attachments(): array
{
return [];
}
}
Create controller
php artsan make:controller MailController
app\Http\Controllers\mailController.php like as below code
<?php
namespace App\Http\Controllers;
use App\Mail\SendEmail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class MailController extends Controller
{
public function sendEmail(Request $request)
{
$variable="Hello artisan!";
$recipient='hello.laravelexample@gmail.com';
Mail::to($recipient)->send(new SendEmail($variable));
return response()->json(['success'=>'Send email successfully.']);
}
}
Create email template blade file
resource\email\email-template.blade.php like as below code
<!DOCTYPE html>
<html>
<body>
<title>https://www.laravelexample.com</title>
<h2>{{$variable}}</h2>
<p>This is example of laravel 12 email.</p>
</body>
</html>
Run Laravel App:
Now Run your laravel 12 app after run these below commands
php artisan serve
Go to your web browser, hit this URL http://localhost:8000/send-email and see your laravel app output:
No comments: