Yii2 - mailer - send message to email rows in database

1.2k views Asked by At

Greetings,

i need to send email to several recipients that are stored in a table named mail which has a field called email.

In my controller i created an action that Query the table mail for the emails.

Later i tried to use the implode() function separated by comma, but obviously it didn't work because of mailer policies. It generated the wrong format -> "[email protected], [email protected], [email protected]".

Tried also a for each loop and the serialize() function without success.

The json_encode() function is close to what i need, separate an array of emails to something like -> "[email protected]", "[email protected]", "[email protected]". But it appends the field name before the value and it is not accepted by mailer policies.

So far i'm stuck with the following code:

public function actionSucesso()
{
    $query = new Query;
    $query->select('email')
    ->from('mail');
    $command = $query->createCommand();
    $enderecos = $command->queryAll();

    $enviar = json_encode($enderecos);

    Yii::$app->mailer->compose()
        ->setFrom('[email protected]')
        ->setTo($enviar)
        ->setSubject('Oferta de jogo no site da ATF.')
        ->setTextBody('Aceda em: http://atf.besaba.com/index.php?r=playschedule%2Findex2')
        ->send();
    return $this->render('sucesso');
}

I think in order for the mailer to work and send the message the correct format needs to be: ->setTo("[email protected]", "[email protected]", "[email protected]")

Is there a way of solving this problem? Many thanks in advance.

1

There are 1 answers

10
Tony On BEST ANSWER

To get array of email with numeric indexes call queryAll() method with $fetchMode parameter \PDO::FETCH_COLUMN, and then just pass returned array to mailer's setTo() method. Like this

$enderecos = $command->queryAll(\PDO::FETCH_COLUMN);

//$enviar = json_encode($enderecos); <- this line no needed

Yii::$app->mailer->compose()
    ->setFrom('[email protected]')
    ->setTo($enderecos) //you pass an array of email addresses
    ->setSubject('Oferta de jogo no site da ATF.')
    ->setTextBody('Aceda em: http://atf.besaba.com/index.php?r=playschedule%2Findex2')
    ->send();

See queryAll() documentation and list of pdo constant including available fetch modes starting with PDO::FETCH_. Also assuming you are using yii2 default mailer, look for swiftmailer documentation about how to set recipients