Search code examples
yii2swiftmaileryii2-basic-app

Yii2 swiftmailer foreach multiple email


I want to run a code to send email to all users. At first i used this code to run a test.

->setTo([
                'john.doe@gmail.com' => 'John Doe',
                'jane.doe@gmail.com' => 'Jane Doe',
        ])

I found out that the mail is 1 mail sent to multiple recipents, while i need to 2 emails to 2 recipients. Because in reality i need to send to over hundred people at once. SO i try foreach loop.

   public function contact($email)
    {
        $users = Users::find()->all();
        $content = $this->body;
    foreach($users as $user){
        if ($this->validate()) {
            Yii::$app->mailer->compose("@app/mail/layouts/html", ["content" => $content])

                ->setTo($user->email)
                ->setFrom($email)
                ->setSubject($user->fullname . ' - ' . $user->employee_id . ': ' . $this->subject)
                ->setTextBody($this->body)
                ->send();

            return true;
        }
    }
        return false;

    }

But it only run 1 loop and end. Please tell me where i'm wrong. Thank you


Solution

  • the reason just one mail is sent is the

    return true
    

    it returns after the first email is sent, you should use try{}catch(){} like below

    public function contact($email) {
            $users = Users::find()->all();
            $content = $this->body;
    
            try {
                foreach ($users as $user) {
                    if ($this->validate()) {
                        $r = Yii::$app->mailer->compose("@app/mail/layouts/html", ["content" => $content])
                                ->setTo($user->email)
                                ->setFrom($email)
                                ->setSubject($user->fullname . ' - ' . $user->employee_id . ': ' . $this->subject)
                                ->setTextBody($this->body)
                                ->send();
                        if (!$r) {
                            throw new \Exception('Error sending the email to '.$user->email);
                        }
                    }
                }
                return true;
            } catch (\Exception $ex) {
                //display messgae
                echo $ex->getMessage();
                //or display error in flash message
                //Yii::$app->session->setFlash('error',$ex->getMessage());
                return false;
            }
        }
    

    You can either return false in the catch part or return the error message rather than returning false and where ever you are calling the contact function check it the following way.

    if(($r=$this->contact($email))!==true){
        //this will display the error message
        echo $r;
    }