Just, send an email

Through the years it seems like Laravel has frequently changed its mind on how to send emails. This example shows the most basic way to send an email without having to rely on envelopes, addresses, factories or actions.

Laravel2 / 3Level:

While Laravel provides many ways of building an email to allow for customization, I found this way to be the most straight-forward:

use Illuminate\Support\Facades\Mail;
use Illuminate\Mail\Mailable as Message;

Mail::send((new Message)
    ->to('johndoe@domain.com', 'John Doe')
    ->subject('My awesome email')
    ->view('mail.basic')
);

That's it. 😏 As long as your SMTP credentials are valid, you are on your way. If you're like "yeah, how else would you do it?", congratulations. 👏 I just happen to be the kind of person who initially tends to treat these things like spacecrafts. 🛸

P.s. In case you're wondering: I used an alias for Mailable, because... well, I find Message way more readable. Just a personal preference, doesn't have anything to do with the rest of the code.

🎁 Bonus

For those who are a fan of convenient helpers:

use Illuminate\Support\Facades\Mail;
use Illuminate\Mail\Mailable as Message;

if (! function_exists('email')) {
    /**
     * Just, send an email.
     *
     * @param  string  $to  The email recipient.
     * @param  string  $subject  The email subject.
     * @param  string  $view  The name of the Blade view.
     * @param  array  $data  The data for the Blade view.
     * 
     * @return \Illuminate\Mail\SentMessage|null
     */
    function email(string $to, string $subject, string $view, array $data = null) {
      return Mail::send((new Message)->to($to)->subject($subject)->view($view, $data);
    }
};

Which would look like this in practice:

// it doesn't get more concise than this, right? 
email(
  to:'elon@x.com', 
  subject:'eXample 🥁', 
  view:'mail.example', 
  data:['logo' => 'x']
);

Conclusion

These examples demonstrate a more efficient way of sending an email using Laravel. While some may argue that it's obvious, or it's actually limiting your options, I personally consider the easiest solutions to be the most effective.

Thank you for reading! 👍