How to mail send in laravel
In Laravel, you can send emails using the built-in Mail facade. Here's a step-by-step guide on how to send an email in Laravel:
Step 1: Install the Mail Package
If you haven't already, install the Mail package by running the following command in your terminal:
composer require illuminate/mail
Step 2: Configure the Mail Settings
In your config/mail.php
file, configure the mail settings. You can set the mail driver, host, port, username, and password. For example:
'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'smtp.gmail.com'),
'port' => env('MAIL_PORT', 587),
'from' => [
'address' => env('MAIL_FROM_ADDRESS', '[email protected]'),
'name' => env('MAIL_FROM_NAME', 'Your Name'),
],
'to' => [
'address' => env('MAIL_TO_ADDRESS', '[email protected]'),
'name' => env('MAIL_TO_NAME', 'Recipient Name'),
],
Step 3: Create a Mail Message
Create a new mail message by creating a new class that extends the Illuminate\Mail\Mailable
class. For example, create a WelcomeEmail
class:
// app/Mail/WelcomeEmail.php
namespace App\Mail;
use Illuminate\Mail\Mailable;
class WelcomeEmail extends Mailable
{
public $user;
public function __construct($user)
{
$this->user = $user;
}
public function build()
{
return $this->markdown('emails.welcome');
}
}
Step 4: Define the Email Template
Create a new email template in the resources/views/emails
directory. For example, create a welcome.blade.php
file:
<!-- resources/views/emails/welcome.blade.php -->
<h1>Welcome {{ $user->name }}!</h1>
<p>Thank you for signing up!</p>
<p>Your account has been created successfully.</p>
Step 5: Send the Email
In your controller or service, create a new instance of the WelcomeEmail
class and send it using the Mail::send
method:
// app/Http/Controllers/AuthController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Mail\WelcomeEmail;
class AuthController extends Controller
{
public function register(Request $request)
{
// Create a new user
$user = User::create($request->all());
// Send a welcome email
Mail::send(new WelcomeEmail($user));
return redirect()->route('home');
}
}
Step 6: Run the Mail Queue
To send the email, you need to run the mail queue. You can do this by running the following command in your terminal:
php artisan queue:work
Alternatively, you can use a scheduler like Laravel's built-in scheduler or a third-party package like Laravel Horizon to run the mail queue.
That's it! With these steps, you should be able to send an email in Laravel.