memo
memo

Reputation: 7

yii and Swift Mailer extension sending last email row twice

Whats wrong with this code which is sending last email row twice? Using yii and Swift Mailer extension

            $emails = Newsletter::model()->findAll();
            if ($emails) {
                $sent = 0;
                foreach ($emails as $row) {
                    $secret = $this->createAbsoluteUrl('/site/newsletter/unsubscribe?s='.$row->secret.'');
                    $email = new YiiMailMessage();
                    $email->setBody($model->body.'<br /><br /><small>Se você não deseja mais receber nossos e-mails,</small> <a style="color:#336699;" href="'.$secret.'">clique aqui</a>', 'text/html', 'utf-8');
                    $email->addTo($row->email);
                    $email->from = Yii::app()->config->get('from_email');
                    $email->setSubject($model->subject);
                    Yii::app()->mail->send($email);
                    $sent++;
                }
                if (!Yii::app()->mail->send($email)) {
                    Yii::app()->user->setFlash('error', 'Não conseguiu enviar mensagem');
                }
                Yii::app()->user->setFlash('success', ''.$sent.' E-mails enviados com sucesso.');
            } else {
                Yii::app()->user->setFlash('error', 'Não há assinantes de enviar a newsletter para.');
            }

Upvotes: 0

Views: 1782

Answers (1)

Choo
Choo

Reputation: 233

The problem is the following string:

if (!Yii::app()->mail->send($email)) {

Here you are sending the last message again and also you are checking only if this last attempt was successful, not all. I'm not sure what exactly do you need cause can't even translate error message, but it will work like a charm:

$emails = Newsletter::model()->findAll();
if ($emails) {
    $sent = 0;
    foreach ($emails as $row) {
        $secret = $this->createAbsoluteUrl('/site/newsletter/unsubscribe?s='.$row->secret.'');
        $email = new YiiMailMessage();
        $email->setBody($model->body.'<br /><br /><small>Se você não deseja mais receber nossos e-mails,</small> <a style="color:#336699;" href="'.$secret.'">clique aqui</a>', 'text/html', 'utf-8');
        $email->addTo($row->email);
        $email->from = Yii::app()->config->get('from_email');
        $email->setSubject($model->subject);
        if (Yii::app()->mail->send($email)) $sent++;
    }
    if ($sent != count($emails)) {
        Yii::app()->user->setFlash('error', 'Não conseguiu enviar mensagem');
    }
    Yii::app()->user->setFlash('success', ''.$sent.' E-mails enviados com sucesso.');
} else {
    Yii::app()->user->setFlash('error', 'Não há assinantes de enviar a newsletter para.');
}

Here I increment $send variable only if message was sent and in the end I check if number of emails attempted to send equals number of successfully sent messages.

Upvotes: 0

Related Questions