Himanshu SharmaSoftware engineer
Let’s talk

Laravel · Lesson 33 of 40

Sending mail from Laravel

Build mailables with Markdown templates, send a contact message and queued admin notices, and read the log mail driver output before using real SMTP.

14 minBackground work and cachingUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonCreate two mailables, send them from a controller and a queued listener, read the result in the log mail driver, and know which .env keys a real mail server needs.

What you can do after this lesson

You will make Pagelane Books send two kinds of email: a message to the shop when someone uses the contact form, and a notification to every administrator when a review is posted. You will test both without any mail server.

Mailables

A mailable is a class that describes one email. Generate them with a Markdown template, which gives you a ready, responsive layout:

bash
php artisan make:mail ContactReceived --markdown=mail.contact-received
php artisan make:mail ReviewReceived --markdown=mail.review-received
text
   INFO  Mailable [app/Mail/ContactReceived.php] created successfully.
   INFO  Markdown view [resources/views/mail/contact-received.blade.php] created successfully.

The class has three parts. The envelope holds subject, recipients and reply-to. The content points to the view. The attachments list is empty by default. Here is the finished contact mailable:

php
class ContactReceived extends Mailable
{
    /**
     * @param  array{name: string, email: string, message: string}  $contact
     */
    public function __construct(public array $contact)
    {
    }

    public function envelope(): Envelope
    {
        return new Envelope(
            replyTo: [new Address($this->contact['email'], $this->contact['name'])],
            subject: 'New message from the contact form',
        );
    }

    public function content(): Content
    {
        return new Content(markdown: 'mail.contact-received');
    }
}

Public constructor properties become variables in the view. Notice that the visitor's address goes into reply-to, not from. The sender stays the shop's own configured address, because mail that claims to come from someone else's domain is often rejected or marked as spam. When an administrator presses reply, the answer goes to the visitor. The template uses Markdown with Blade components:

blade
<x-mail::message>
## New contact message

**From:** {{ $contact['name'] }} ({{ $contact['email'] }})

{{ $contact['message'] }}

<x-mail::button :url="route('home')">
Open the shop
</x-mail::button>

Thanks,<br>
{{ config('app.name') }}
</x-mail::message>

The generated stub used a top-level # heading; we used ## so the email stays tidy. Values printed with double braces are escaped as in any Blade view.

Sending

In ContactController@store, after validation:

php
Mail::to(config('shop.contact_email'))->send(new ContactReceived($validated));

shop.contact_email is the config key you added in the configuration lesson's exercise, with the fake default hello@example.com. Mail::to() accepts an address, a user model or a collection of users. send() delivers immediately, inside the request; for slower providers use Mail::to(...)->queue(...) or send from a queued listener.

The log driver

.env has MAIL_MAILER=log. Nothing leaves your machine: the complete message is written into storage/logs/laravel.log. After submitting the contact form, the log held:

text
From: Pagelane Books <hello@example.com>
To: hello@example.com
Reply-To: Ada Reader <ada.reader@example.com>
Subject: New message from the contact form
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary=...

followed by a plain-text part:

text
Pagelane Books: http://localhost:8000

## New contact message

**From:** Ada Reader (ada.reader@example.com)

Do you stock signed copies of Salt and Signal?

Open the shop: http://localhost:8091

and an HTML part with inline styles. (Message ids and boundaries are random; the host in links comes from the current request or APP_URL.) Because log files hold what visitors typed, treat them as personal data: do not share them and rotate them. Other mailers, such as array (used in tests), smtp and provider-specific ones, are configured in config/mail.php.

A queued notification

Now notify administrators when a review arrives. This is the queued listener promised in the events lesson:

php
class NotifyAdminsOfReview implements ShouldQueue
{
    public function handle(ReviewPosted $event): void
    {
        $admins = User::where('is_admin', true)->get();

        if ($admins->isEmpty()) {
            return;
        }

        Mail::to($admins)->send(new ReviewReceived($event->review));
    }
}

php artisan event:list --event=ReviewPosted now shows QueueActivityRecord@handle and NotifyAdminsOfReview@handle (ShouldQueue). A reader posted a review; the queue held 2 jobs (the activity job and the queued listener); after php artisan queue:work --stop-when-empty both ran:

text
  App\Jobs\RecordReviewActivity .................. RUNNING
  App\Jobs\RecordReviewActivity .............. 9.29ms DONE
  App\Listeners\NotifyAdminsOfReview ............. RUNNING
  App\Listeners\NotifyAdminsOfReview ........ 46.89ms DONE

The log gained a message To: Shop Admin <admin@example.com>, with the subject New review for <book title> and the text "Test Reader rated ... 5 out of 5." The review post itself returned immediately, with no mail work in the request.

Real delivery

When you are ready for real email, you choose a provider and put its settings in the real .env. Typical SMTP keys look like this, with fake values:

text
MAIL_MAILER=smtp
MAIL_HOST=smtp.example.com
MAIL_PORT=587
MAIL_USERNAME=shop-mailer
MAIL_PASSWORD=change-me-fake-value
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"

Use an address on a domain you control, set up the provider's authentication records (SPF and DKIM) as it instructs, and send a test message before launch. Never commit the real credentials. Marketing or bulk mail needs consent and unsubscribe handling under the rules where your readers live; this lesson only covers transactional messages.

Common mistakes

  • Using the visitor's address as the sender.
  • Leaving MAIL_MAILER=log in production, where nobody receives anything.
  • Sending mail inside the request when it can be queued.
  • Forgetting to run a queue worker for queued mail.
  • Putting real SMTP passwords in .env.example or Git.

Exercise

Send a confirmation copy to the visitor as well: a second mailable ContactConfirmation that says "We received your message". Where does it go in the controller, and should it be queued?

Show one possible answer
php
Mail::to(config('shop.contact_email'))->send(new ContactReceived($validated));
Mail::to($validated['email'])->queue(new ContactConfirmation($validated['name']));

Create it with php artisan make:mail ContactConfirmation --markdown=mail.contact-confirmation. Queuing is sensible for the visitor's copy because the visitor should not wait for it, but remember that it needs a running worker. Be cautious about sending mail to arbitrary typed addresses without limits, because a contact form can be abused to send unwanted mail; the security lesson returns to throttling. Next: caching.

Key points

  • A mailable is a class describing one email: its envelope (to, subject, reply-to), its content (a Blade or Markdown view) and optional attachments.
  • The fresh project uses MAIL_MAILER=log, which writes the full email into the log file instead of sending it, so you can develop without a mail server.
  • Mail::to($address)->send(new Mailable) sends immediately; a queued listener or queue() moves slow sending out of the request.
  • Real delivery needs MAIL_* settings from a provider, with credentials only in the real .env file, never in Git.
  • Use a reply-to for visitor addresses rather than setting them as the sender, and be careful that logs may contain personal data.

Check yourself

1. What does MAIL_MAILER=log do?
2. Why set the visitor's address as reply-to instead of from?
3. Where do SMTP passwords belong?
4. How can sending mail be kept from slowing the request?