Sending Emails in Laravel

Lesson 37 of 50

74%
1. Introduction to Email in Laravel

Laravel provides a convenient mail system for sending emails from web applications. You can send registration confirmations, password reset links, admission updates, fee receipts, and notifications.

Common uses of email in Laravel:

  • Welcome emails after registration.
  • Password reset emails.
  • Student admission confirmations.
  • Fee payment receipts.
  • Assignment and course notifications.

Laravel uses mail configuration and mail classes to organize email delivery. For this lesson, we will create a simple email that can be sent from a controller.

2. Configure Mail Settings

Laravel reads mail settings from your environment configuration. For local practice, you can use a testing service such as Mailpit or another SMTP provider.

Example SMTP configuration in .env:

MAIL_MAILER=smtp
MAIL_HOST=your-smtp-host
MAIL_PORT=587
MAIL_USERNAME=your-smtp-username
MAIL_PASSWORD=your-smtp-password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="noreply@example.com"
MAIL_FROM_NAME="${APP_NAME}"

Replace the example values with the SMTP settings provided by your email service.

Important:

  • Never publish SMTP credentials in public code repositories.
  • Use the encryption and port required by your provider.
  • Use an authorized sender address for production emails.

After changing configuration, clear the cached configuration if necessary:

php artisan config:clear
3. Create a Mailable Class

A Mailable class defines the content and structure of an email.

Run this Artisan command:

php artisan make:mail WelcomeMail

Laravel creates:

app/Mail/WelcomeMail.php

Open the generated file and configure it:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class WelcomeMail extends Mailable
{
    use Queueable, SerializesModels;

    public function __construct(
        public string $studentName
    ) {}

    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Welcome to Soopro Pathshala'
        );
    }

    public function content(): Content
    {
        return new Content(
            view: 'emails.welcome'
        );
    }
}

The constructor receives the student's name. Laravel makes this public property available to the email view.

4. Create the Email View

Create the following Blade file:

resources/views/emails/welcome.blade.php

Add this content:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Welcome</title>
</head>
<body>
    <h2>Hello {{ $studentName }}!</h2>

    <p>
        Welcome to Soopro Pathshala.
        We are happy to have you as our student.
    </p>

    <p>
        We wish you success in your learning journey.
    </p>
</body>
</html>

The Blade expression {{ $studentName }} displays the name passed from the Mailable class. Blade escapes this output by default.

5. Send an Email from a Controller

Create a controller:

php artisan make:controller EmailController

Open EmailController.php:

<?php

namespace App\Http\Controllers;

use App\Mail\WelcomeMail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class EmailController extends Controller
{
    public function sendWelcomeEmail(Request $request)
    {
        $validated = $request->validate([
            'email' => ['required', 'email'],
            'name' => ['required', 'string', 'max:255'],
        ]);

        Mail::to($validated['email'])->send(
            new WelcomeMail($validated['name'])
        );

        return response()->json([
            'message' => 'Welcome email sent successfully.',
        ]);
    }
}

The controller validates the recipient's email address and name, then sends the Mailable.

In a production application, handle mail delivery failures appropriately. Do not assume an email has reached the recipient's inbox merely because the application accepted the send operation.

6. Create a Route to Send the Email

For a simple demonstration, register a POST route in routes/web.php:

use App\Http\Controllers\EmailController;
use Illuminate\Support\Facades\Route;

Route::post('/send-welcome-email', [
    EmailController::class,
    'sendWelcomeEmail'
]);

This route accepts a POST request containing name and email.

Example form fields:

<form action="/send-welcome-email" method="POST">
    @csrf

    <label>Name:</label>
    <input type="text" name="name" required>

    <label>Email:</label>
    <input type="email" name="email" required>

    <button type="submit">Send Email</button>
</form>

Because this example uses a web route, Laravel's CSRF protection applies. For a production form, also add appropriate authentication, authorization, rate limiting, and recipient verification.

7. Send Emails Using Markdown Templates

Laravel supports Markdown email templates that provide a structured email layout.

Create a Markdown Mailable:

php artisan make:mail AdmissionMail --markdown=emails.admission

Laravel generates a Mailable class and a Markdown Blade template. In the generated Mailable, provide the subject and Markdown view, for example:

public function envelope(): Envelope
{
    return new Envelope(
        subject: 'Admission Confirmation'
    );
}

public function content(): Content
{
    return new Content(
        markdown: 'emails.admission'
    );
}

Edit the generated resources/views/emails/admission.blade.php file:

<x-mail::message>
# Admission Confirmed

Your admission request has been received successfully.

Thank you for choosing Soopro Pathshala.

Regards,
Soopro Pathshala </x-mail::message>

Markdown mail templates can help create consistent email layouts with headings, buttons, and other supported components.

8. Send Emails Using Queues

Sending email synchronously can make a request take longer. Queues let Laravel process email work in the background when a queue worker is running.

To queue a Mailable, implement ShouldQueue:

use Illuminate\Contracts\Queue\ShouldQueue;

class WelcomeMail extends Mailable implements ShouldQueue
{
    // Keep the existing Mailable implementation here.
}

Keep the constructor, envelope, and content methods from the earlier example in the same class.

Then use queue() instead of send():

Mail::to($validated['email'])->queue(
    new WelcomeMail($validated['name'])
);

Configure a queue connection and its required storage first. For a database queue, create the jobs table if your project does not already have it:

php artisan make:queue-table
php artisan migrate

Run the queue worker:

php artisan queue:work

The queue worker must remain running to process queued jobs. Production deployments usually run it through a process manager.

9. Practice Assignment and Best Practices

Complete the following tasks:

  1. Configure SMTP settings in the Laravel environment.
  2. Create a WelcomeMail Mailable.
  3. Create an email Blade template.
  4. Create a controller method to send a welcome email.
  5. Register a POST route and submit a test form.
  6. Create a Markdown email for admission confirmation.
  7. Configure a queue and send an email asynchronously.

Best practices:

  • Never commit SMTP passwords or API keys to source control.
  • Validate recipient addresses and user input.
  • Use queues for emails that should not delay web requests.
  • Log delivery errors without exposing secrets.
  • Use verified sender domains and proper email authentication in production.
  • Test emails with a development mail catcher before sending real messages.
Quick Quiz

1. Which Artisan command creates a Mailable class?




2. Which facade is commonly used to send emails?




3. What is a major benefit of queuing emails?