SpaceDogCS
SpaceDogCS

Reputation: 2978

Laravel Email, send multiples e-mails

I'm trying to send a mail to multiples providers

$email['success'] is equals to:

0 => {
  'name' => 'Quimer Comercial Ltda.',
  'email' => '[email protected]'
},
1 => {
  'name' => 'Doce Aroma Industria e Comercio - 47'
  'email' => '[email protected]'
},
2 => {
  'name' => 'Purifarma Distr.quimica e Farmac. Ltda.'
  'email' => '[email protected]'
}

That is my code:

$mail = new NewCotacao($codigoempresa, $codigocotacao);
foreach($emails['success'] as $email){
    Mail::to($email['email'])->send($mail);
}

But look what is happening

enter image description here

I want to looks like this to each one

To: [email protected]

To: [email protected]

To: [email protected]

Upvotes: 0

Views: 215

Answers (1)

Ben
Ben

Reputation: 5139

You should create separate Mailable to each user:

foreach($emails['success'] as $email){
    $mail = new NewCotacao($codigoempresa, $codigocotacao);
    Mail::to($email['email'])->send($mail);
}

If you are using same Mailable instance, the recipients will get appended.

// Extracted from vendor source code
// File: illuminate/mail/Mailable.php

/**
 * Set the recipients of the message.
 *
 * @param  object|array|string  $address
 * @param  string|null  $name
 * @return $this
 */
public function to($address, $name = null)
{
    return $this->setAddress($address, $name, 'to');
}

/**
 * Set the recipients of the message.
 *
 * All recipients are stored internally as [['name' => ?, 'address' => ?]]
 *
 * @param  object|array|string  $address
 * @param  string|null  $name
 * @param  string  $property
 * @return $this
 */
protected function setAddress($address, $name = null, $property = 'to')
{
    foreach ($this->addressesToArray($address, $name) as $recipient) {
        $recipient = $this->normalizeRecipient($recipient);
        $this->{$property}[] = [
            'name' => $recipient->name ?? null,
            'address' => $recipient->email,
        ];
    }
    return $this;
}

Upvotes: 1

Related Questions