Sending Emails in Laravel

We can configure sending emails very easily in Laravel. If you already have a service that provides your hosting or similar, all you have to do is create an email address with its password.

From here, you must configure some parameters. If you do not know them because the email server you are using is a service, you must ask your service providers; in the case of Hostinger they would be the following:

config/mail.php

'smtp' => [
       'transport' => 'smtp',
       'host' => env('MAIL_HOST', 'smtp.hostinger.com'),
       'port' => env('MAIL_PORT', 465),
       'encryption' => env('MAIL_ENCRYPTION', 'ssl'),
       'username' => env('MAIL_USERNAME','<EMAIL>'),
       'password' => env('MAIL_PASSWORD',"<PASSWORD>"),
       'timeout' => null,
       'auth_mode' => null,
],

Or you can use a testing service in case you don't have access to a real email server like mailtrap:

https://mailtrap.io

In which, you must go to the previous page, create an account that is completely free, create an inbox and configure your project.

.env

MAIL_MAILER=smtp
MAIL_HOST=sandbox.smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=ec5cbede982042
MAIL_PASSWORD=********0be7

Mailable class

To send any email, we must use a class, just as when we define a model, controller or request, we must create a class with a specific structure:

app\Mail\OrderShipped.php

<?php
namespace App\Mail;

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

class OrderShipped extends Mailable
{

    public $email;
    public $title;
    public $content;

    use Queueable, SerializesModels;

    public function __construct($email, $title, $content)
    {
        $this->email = $email;
        $this->title = $title;
        $this->content = $content;
    }

 
    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Order Shipped',
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'emails.subscribe',
        );
    }

    /**
     * Get the attachments for the message.
     *
     * @return array<int, \Illuminate\Mail\Mailables\Attachment>
     */
    public function attachments(): array
    {
        return [];
    }
}

To do this, we use the command:

$ php artisan make:mail OrderShipped

We use the envelope() method to define the subject, the content() method for the body of the message, there we specify the view and the attachments() method for attached files, the constructor is basic in PHP classes and is used to initialize properties or other tasks when creating the object or instance of the class.

We also defined some example properties such as the title, content and email, you can create others or modify the defined ones according to your needs.

We can also use a single method to define the subject and content:

app\Mail\SubscribeEmail.php

<?php
namespace App\Mail;

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

class SubscribeEmail extends Mailable
{
    use Queueable, SerializesModels;

    public $email;
    public $title;
    public $content;

    public function __construct($email, $title, $content)
    {
        $this->email = $email;
        $this->title = $title;
        $this->content = $content;
    }

    public function build()
    {
        return $this->subject($this->title)->view('subscribe');
    }
}

From it, we can customize the arguments to receive, such as email subject or email content, and return a blade view that corresponds to the body of the email; for example:

We create the view that can have any format:

resources\views\emails\subscribe.blade.php

<p>Hi<br>
{!! $content !!}

Send emails individually

To send the emails, we create an instance as follows:

Mail::to('no-reply@example.net.com')->send(new SubscribeEmail('contact@gmail.com', $title, $content));

Parameters

You are not limited to simply specifying "to" recipients when sending a message. You are free to configure "to", "cc" and "bcc" recipients using their respective methods:

Mail::to($request->user())
    ->cc($moreUsers)
    ->bcc($evenMoreUsers)
    ->send(new SubscribeEmail(contact@gmail.com', $title, $content));

CC and BCC/CCO

A CC is a way of sending additional copies of an email to other people "carbon copy", while BCC is the same as the CC but this list of recipients or people remain hidden, that is, they do not appear in the signature of the email.

Send mass emails

One of the ways in which we can send multiple emails in bulk or batch is to send multiple emails in the same contact. This is usually a delicate case since, if we do something like the following:

Mail::to('no-reply@example.net.com')
   ->cc(['hideemail1@gmail.com','hideemail2@gmail.com','hideemail3@gmail.com'])->send(new SubscribeEmail(contact@gmail.com', $title, $content));

The email will expose all the users' emails, a situation that is usually a problem due to the exposure of all emails to all recipients; instead of using the cc option we can use the bcc option which allows us to hide the recipients:

Mail::to('no-reply@example.net.com')
   ->bcc(['hideemail1@gmail.com','hideemail2@gmail.com','hideemail3@gmail.com'])->send(new SubscribeEmail(contact@gmail.com', $title, $content));

Now we will see that the emails defined in BBC appear hidden:

 

Email header

 

And not present as in the previous image.

- Andrés Cruz

En español

This material is part of my complete course and book; You can purchase them from the books and/or courses section, Curso y libro Laravel 11 con Tailwind Vue 3, introducción a Jetstream Livewire e Inerta desde cero - 2024.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.