phplaravelemaillaravel-5bulk-email

Sending bulk emails using different credentials


I need to send hundreds of emails using different credentials from laravel. Each customer of mine has his/hers mail list and needs to provide their own SMTP server. I process that list and send emails on customer's behalf.

This is what I have so far. It is working, but it is very slow and I don't have many emails so far. I see a problem when I get more emails. Any suggestions on how to improve?

PS- I use cron Console Command and use Kernel to schedule the job.

public function sendMailings($allMailings) {

    foreach ($allMailings as $email) {
        Config::set('mail.host', $email['smtpServer']);
        Config::set('mail.port', $email['smtpPort']); 
        Config::set('mail.username', $email['smtpUser']);
        Config::set('mail.password', $email['smtpPassword']); 
        Config::set('mail.encryption', $email['smtpProtocol']);            
        Config::set('mail.frommmail', trim($email['fromEmail'])); 
        Config::set('mail.fromuser', trim($email['fromUser'])); 
        Config::set('mail.subject', trim($email['subject'])); 
        Config::set('mail.toEmail', trim($email['toEmail'])); 
        Config::set('mail.toName', trim($email['toName'])); 
        Config::set('mail.pretend', false); 

        $email_body = $email['emailBody'];

        Mail::send('emails.availability, compact('email_body')
                , function($message) {
            $message->from(config('mail.username'), config('mail.fromUser'));
            $message->replyTo(config('mail.frommmail'), config('mail.fromUser'));
            $message->to(config('mail.toEmail'), config('mail.toName'))->subject(config('mail.subject'));
        }); 
        Log::info('Mail was sent');
    }
}

Solution

  • You can not change email provider configs on-the-fly, so you must make new instance of mailer in service container. I did it before, i wrote a method in my own class to get new mailer instance:

     /**
     * @return Mailer
     */
    protected function getMailer()
    {
        // Changing mailer configuration
        config(['mail.driver' => static::getName()]);
    
        // Register new instance of mailer on-the-fly
        (new MailServiceProvider($this->container))->register();
    
        // Get mailer instance from service container
        return $this->container->make('mailer');
    }