Send email in Laravel without using Mailables

 Reading time ~2 minutes

Introduction

I keep forgetting how to send an email in Laravel without using Mailables. The the documentation does not help so I’m writing this down here for future reference.

The following examples are based on the code of the Mailer class

How to

In order to send a raw message (in plain text) you can use the raw method of the Mail facade:

<?php

Mail::raw('Hello, welcome to Laravel!', function ($message) {
  $message
    ->to(...)
    ->subject(...);
});

On the other hand, an html message can be sent with the html method:

<?php

Mail::html($html, function ($message) {
  $message
    ->to(...)
    ->subject(...);
});

There’s also another method, called plain, which sends plain text emails with variable substitution:

<?php

Mail::plain('Hello {{ $user }}, welcome to Laravel!', ['user' => 'John Doe'], function ($message) {
  $message
    ->to(...)
    ->subject(...);
});

All these 3 methods use send under the hood, so you can actually provide any combination of html, text and raw content:

<?php

Mail::send([
    'html' => $html,
    'text' => 'Hello {{ $user }}, welcome to Laravel!',
    'raw'  => 'Hello, welcome to Laravel!'
], [
    'user' => 'John Doe'
], function ($message) {
  $message
    ->to(...)
    ->subject(...);
});

The priority is always sequential, therefore if the html content is provided then it will be set as body on the Symfony SwiftMailer, otherwise Laravel will try to set either the plain text or the raw part.

As a rule of thumb, if you’re going to send a HTML email, always include a plain-text equivalent of the same content so that users who prefer to read plain text can do so.

You can actually set all the parts yourself, by using directly the SwiftMailer instance:

<?php

Mail::send([], [], function ($message) use ($html) {
  $message
    ->to(...)
    ->subject(...)
    ->setBody($html, 'text/html')
    ->addPart('Hello, welcome to Laravel!', 'text/plain');
});

Finally keep in mind that you cannot queue emails using this method. Only mailables may be queued.

comments powered by Disqus

Implement dynamic custom messages from validation errors in Laravel

Notice: the following article takes into consideration Laravel versions lower than 5.5. After that it is easier to use custom validation …

Remove Laravel Mix during tests

Parse log files with AWK