[Laravel] Send emails to users in batch

Sep 9, 2020 PHP Laravel mailtrap

Continuation is power. A memorandum today as well.

In order to deepen the understanding of batch, I implemented a simple process.

Environment

PHP 7.3.8 Laravel 6.18.35

Today’s topic

Try sending an email in batch. This time, it will be sent in a batch to the registered users of the application to be implemented.

Email preferences

Use an SMTP dummy server called mailtrap.io. It is very convenient because you can check the result on the screen of mailtrap.io without sending the mail sent by using mailtrap.io to the specified address. You can use it immediately after registering as a member.

Go from Inboxes in mailtrap.io to Demo inbox and check the SMTP information. Edit .env based on that information.

MAIL_DRIVER = smtp
MAIL_HOST = smtp.mailtrap.io
MAIL_PORT = 587
Refer to the SMTP information of MAIL_USERNAME = mailtrap.io
Refer to the SMTP information of MAIL_PASSWORD = mailtrap.io
MAIL_ENCRYPTION = null
MAIL_FROM_ADDRESS = [email protected]
MAIL_FROM_NAME = "Example"

Write batch processing

Generate a batch command class.

$ php artisan make: command SendMailCommand
<? php

namespace App \ Console \ Commands;

use Illuminate \ Console \ Command;
use App \ User;
// Facade for sending emails
use Illuminate \ Support \ Facades \ Mail;


class SendMailCommand extends Command
{
    / **
     * The name and signature of the console command.
     *
     * @var string
     * /
    // Command name
    protected $ signature ='users: send_mail';

    / **
     * The console command description.
     *
     * @var string
     * /
    protected $ description ='Batch description';

    / **
     * Create a new command instance.
     *
     * @return void
     * /
    public function __construct ()
    {
        parent :: __ construct ();
    }

    / **
     * Execute the console command.
     *
     * @return mixed
     * /
    public function handle ()
    {
        // Extract user information from the model
        $ users = User :: all ();
        // Repeat with email address
        foreach ($ users as $ user) {
            echo $ user ['email']. "\ n";

            Mail :: raw ("I'm emailing this in batch", function ($ message) use ($ user)
            {
                // to to destination, subject to subject
                $ message-> to ($ user-> email)-> subject ('test');
            });
        }
    }
}

This completes the batch

but~ Even if you execute the batch command as it is, it may fail.

 Swift_TransportException: Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required

When this happens, let’s clear the cache.

$ php artisan cache: clear
$ php artisan config: cache

Execute batch command again

php artisan users: send_mail

Let’s check if it is received correctly with mailtrap.io. Screenshot 2020-09-09 23.36.02.png It’s working!

Reference

Outgoing mail server settings in Laravel 5