Send group emails via notifications

Submitted by DavertMik - 5 years ago

It's easy to notify one user by mail. But how to send a mail to all members of a Team? You can send one email to multiple recipients but it's not convenient, as it discloses recipient emails, which is not secure. Thus, you need to send bunch of personal emails on a loop. To do this create new TeamMailChannel and get MailChannel inside of it. Then iterate over users of a group and send emails. Your notification class should include TeamMailChannel inside via, however you should still use `toMail` method to prepare a message.

<?php
namespace App\Notifications;

use App\Team;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Channels\MailChannel;

class TeamMailChannel
{
    protected $mailChannel;

    public function __construct(MailChannel $mailChannel)
    {
        $this->mailChannel = $mailChannel;
    }

    public function send(Team $team, Notification $notification)
    {
        foreach ($team->users as $user) {
            $this->mailChannel->send($user, $notification);
        }

    }
}

// inside notification file:
class GroupNotification
{
    public function via($notifiable)
    {
        return [TeamMailChannel::class];
    }
    
    // please 
    public function toMail($notifiable)
    {
        return new MailMessage;   
    }