Send mails in Laravel with Example [100% Working]


Written By - Steve Alila
Advertisement

Laravel Mail provides a simple and elegant way to send emails from your web applications, allowing you to keep your users informed and engaged. In this article, we will walk you through the process of configuring the email driver, creating a mailable, and send mails in Laravel.

Whether you are a seasoned developer or a beginner, you will find this guide helpful in learning the basics of Laravel Mail and how to use it effectively in your projects.

So, let's get started!

 

Step~1: Configure Email Driver

Laravel supports email sending through SMTP, Mailgun, Postmark, Amazon SES, and sendmail drivers. Through an email API powered by Symfony Mailer component, you can quickly start sending mails through your preferred local or cloud-based service. You can find the main drivers and their sample configuration entries in the mailers configuration array in the config/mail.php file.

To configure your email driver, choose the driver that best suits your needs and set it up in .env file. For example, to set up SMTP, you would set the MAIL_DRIVER to smtp and configure the MAIL_HOST, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD, and MAIL_ENCRYPTION variables with your email server details.

For instance, if you're using Gmail as your email provider, the settings would look like this:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your-email@gmail.com
MAIL_PASSWORD=your-email-password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=your-email@gmail.com
MAIL_FROM_NAME="${APP_NAME}"

I am using Mailtrap and my details are as follows:

MAIL_MAILER=smtp
MAIL_HOST=sandbox.smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=my-uname-id
MAIL_PASSWORD=secure-pwd-id
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=admin@golinuxcloud.com
MAIL_FROM_NAME="${APP_NAME}"

Send mails in Laravel with Example [100% Working]

 

Step~2: Create a Mailable

Once you've filled in your email settings in the .env file, you will need to create a Mailable. A Mailable is a PHP class that represents an email message and contains the logic for building the message.

Advertisement

Use the php artisan make:mail command to create a Mailable.

php artisan make:mail ThankYouMail

For example the above command creates a new Mailable named ThankYouMail in the app/Mail directory.

<?php

namespace App\Mail;

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

class ThankYouMail extends Mailable
{
    use Queueable, SerializesModels;

    public $note;

    /**
     * Create a new message instance.
     */
    public function __construct($note)
    {
        $this->note = $note;
    }

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

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

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

The envelope method returns an Illuminate\Mail\Mailables\Envelope object. The object defines the subject and (sometimes) the body of the message.

 

How to send HTML email in Laravel?

The content method returns an Illuminate\Mail\Mailables\Content object. The object defines the Blade template to be used when generating the message content. The emails.thankYou points to resources/views/emails/thankYou.blade.php file. It is the view template that will be sent to the recipient.

Send mails in Laravel with Example [100% Working]

 

How to send email with attachments in Laravel?

Lastly, the attachments method lets you add attachments to array returned from the Attachment class. You can specify the attachment's location in the attachments method. Alternatively, you can return the attachedFile attribute.

 Attachment::fromPath($this->attachedFile),

and attach the file in a controller.

// routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Mail\ThankYouMail;

Route::get('/testroute', function () {
    $filePath = public_path('image1.png');
    $name = "First Image";
    Mail::to('johndoe@company.net')->send(new ThankYouMail($name, $filePath));
});

Leave the array empty if you don't plan to send any attachment.

 

Step~3: Send Mails in Laravel

The Mail facade lets you send mails in Laravel. Call the send method on the Mailable object to send the email. For example, Mail::to('salmamohamed@gmail.com')->send(new ThankYouMail()); sends an email to salmamohamed@gmail.com using the ThankYouMail Mailable.

<?php

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Mail\ThankYouMail;
use Illuminate\Support\Facades\Mail;

class ThankYouMailController extends Controller
{
    public function index()
    {
        $note = 'Hey, Salma. Thank you so much for buying me a cup of coffee!';
        Mail::to('salmamohamed@gmail.com')->send(new ThankYouMail($note));
        return redirect('/');
    }
}

Send emails in Laravel

 

Additionally, you can customize the mail by attaching more Mail facade methods. For example, you can append cc, bcc, and queue methods.

Mail::to('salmamohamed@gmail.com')
    ->cc($moreUsers)
    ->bcc($evenMoreUsers)
    ->queue(new ThankYouMail($note));

->cc($moreUsers) adds one or more email addresses to the "carbon copy" (CC) list of the email, meaning that they will receive a copy of the email as well. $moreUsers is a variable that should contain an array of email addresses that you want to include in the CC list.

Similarly, ->bcc($evenMoreUsers) adds one or more email addresses to the "blind carbon copy" (BCC) list of the email, meaning that they will receive a copy of the email as well, but their email addresses will not be visible to other recipients. $evenMoreUsers is a variable that should contain an array of email addresses that you want to include in the BCC list.

->queue(new ThankYouMail($note)) queues up the email to be sent in the background, rather than sending it immediately. The ThankYouMail class is responsible for generating the actual content of the email. $note is a variable that contains the data needed by the ThankYouMail class to generate the email's content.

 

How to send emails to multiple recipients in Laravel?

You can also send emails to multiple recipients. Here is an example.

$recipients = [
  'First Coder' => 'hiteshchoudhary@gmail.com',
  'Second Coder' => 'eltonjames@gmail.com', 
  'Third Coder' => 'abdishakur@gmail.com'
]
foreach ($recipients as $name => $recipient) {
    Mail::to($recipient)->send(new ThankYouMail($name));
}

The $recipients array contains the names and email addresses of the recipients. Each recipient is represented by a key-value pair, where the key is the name of the recipient and the value is their email address.

The foreach loop iterates over each recipient in the $recipients array. In each iteration, the Mail::to($recipient) method is called to specify the recipient's email address for the email.

The send method, chained to the Mail::to() call, sends the email. The method takes an instance of the ThankYouMail class as its argument, which is responsible for composing the email content.

Inside the ThankYouMail class, the recipient's name is passed as a parameter to the constructor. This allows the email template to be personalized with the recipient's name.

 

How to send email in Laravel using a transactional email API?

A transactional email API provides you with a set of methods and endpoints that you can integrate into your applications to send transactional emails. Transactional emails are messages triggered by specific user actions or events, such as account registrations, password resets, order confirmations, and notifications.

For example, through the Mailtrap PHP SDK, you can integrate emails in your Laravel application. First, install the Mailtrap PHP client using composer.

composer require railsware/mailtrap-php symfony/http-client nyholm/psr7

In the config/mail.php file, add the Mailtrap transport.

<?php

return [
    /*
    |--------------------------------------------------------------------------
    | Mailer Configurations
    |--------------------------------------------------------------------------
    */
    'mailers' => [
            'mailtrap' => [
                'transport' => 'mailtrap'
            ],
    ]
];

Next, add your Mailtrap credentials to the .env file.

MAIL_MAILER="mailtrap"
MAILTRAP_HOST="send.api.mailtrap.io"
MAILTRAP_API_KEY="YOUR_API_KEY_HERE"
MAILTRAP_INBOX_ID=1000001

You can then add a mailable class and configure it before adding an email template, as we did when sending emails with SMTP server.

Next, add the CLI router to the app/routes/console.php file.

<?php

use App\Mail\WelcomeMail;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Mail;

Artisan::command('send-thanks-mail', function () {
    Mail::to('testreceiver@gmail.com')->send(new ThankYouMail("Jon"));
})->purpose('Send Thanks mail');

And call the CLI command.

php artisan send-thanks-mail

 

Conclusion

Sending mails in Laravel is made straightforward and efficient with Laravel Mail. This robust feature equips developers to effortlessly dispatch emails from their Laravel projects. Boasting a lucid and expressive API, Laravel Mail caters to a range of email types, from plain text and HTML to attachments and verification links.

The inherent email attributes of Laravel simplify not just the sending, but also the management of emails within applications. Furthermore, when aiming to send mails in Laravel, developers have the flexibility to choose from a variety of service providers like SMTP, Mailgun, and Amazon SES, ensuring a seamless mailing experience.

One of the standout advantages of Laravel Mail is its provision for developers to test email functions during the developmental phase. This ensures that email layouts and configurations are perfectly aligned with their intended purposes.

In essence, for Laravel developers eager to incorporate email features, Laravel Mail is indispensable. It not only simplifies the mailing process but also enhances the overall experience for developers and recipients alike.

You can read more at Mail - Laravel 8.x - The PHP Framework For Web Artisans

 

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment