Laravel mail to
In Laravel, you can send emails using the Mail
facade. Here's a step-by-step guide on how to send an email in Laravel:
Step 1: Create a Mail Class
In Laravel, you need to create a mail class that extends the Illuminate\Mail\Mailable
class. This class will define the email template and the data that will be sent in the email.
For example, let's 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');
}
}
In this example, the WelcomeEmail
class has a constructor that takes a user
object as an argument. The build
method returns a Mailable
instance that uses the markdown
method to render the email template.
Step 2: Create an Email Template
Create a new file in the resources/views/emails
directory, for example, welcome.blade.php
:
<!-- resources/views/emails/welcome.blade.php -->
<h1>Welcome {{ $user->name }}!</h1>
<p>Thank you for signing up for our service.</p>
<p>Your account has been created successfully.</p>
<p>Best regards,</p>
<p>Your Name</p>
This is a simple email template that uses Blade syntax to display the user's name.
Step 3: Send the Email
To send the email, you can use the Mail
facade:
// app/Http/Controllers/AuthController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Mail\WelcomeEmail;
use Illuminate\Support\Facades\Mail;
class AuthController extends Controller
{
public function register(Request $request)
{
// Create a new user
$user = User::create($request->all());
// Send a welcome email
Mail::to($user->email)->send(new WelcomeEmail($user));
return redirect()->route('home');
}
}
In this example, the AuthController
sends a welcome email to the newly created user using the Mail
facade. The Mail
facade takes the email address and the WelcomeEmail
instance as arguments, and sends the email.
Step 4: Configure the Mail Driver
By default, Laravel uses the smtp
mail driver. You can configure the mail driver in the config/mail.php
file:
// config/mail.php
'driver' => env('MAIL_DRIVER', 'smtp'),
You can also configure the mail driver using environment variables:
MAIL_DRIVER=smtp
That's it! With these steps, you should be able to send emails in Laravel using the Mail
facade.