how to send mail using swiftmailer - Yii2

1.4k Views Asked by At

I tried to send email using swiftmailer in Yii2. I'm still beginner for this framework. This is my basic code:

public function sendMail($email)
    {
        if ($this->validate()) {
            $email = Yii::$app->params['adminEmail'];
            $mailto = '[email protected]'; // need to change
            $isi = "blablabla";

            Yii::$app->mailer->compose("@app/mail/layouts/html", ["content" => $isi])
                ->setTo($mailto)
                ->setFrom($email)
                ->setSubject('coba')
                ->send();

            return true;
        }
        return false;
    }

In my case, I want to setup a 'setTo' based on my usr table. Field of my usr table:

id | username | manager | email           | type     |
1  | fauzi    | arie    | [email protected] | user     |
2  | arie     | rian    | [email protected]  | approver |

For example, when user with id = 1 login then he's create a new post and after click submit, the action also send email to user with id = 2 (manager of fauzi) for some review before post is publish to public. Thank you.

1

There are 1 best solutions below

0
On

note: I assume your usr table has model called User if not, then change it to fit your code

you can provide also array of email adresses like

->setTo(['[email protected]', '[email protected]' => 'Name Surname'])

What you want to know is which users you want to get, maybe add some conditions to activerecord etc...

$users = User::find()->all();

or

// or any condition you need in your application, this is just example
$users = User::find()->andWhere(['type' => 'approver'])->all(); 

then Variant #1 you can loop trough all records

foreach ($users as $user) {
    // you can add here some conditions for different types of users etc
    // ... your code to send email ...
    ->setTo([$user->email => $user->username])
    // or just 
    // ->setTo($user->email)
}

or Variant #2 you can get all emails first

$emails = \yii\helpers\ArrayHelper::getColumn($users, 'email');
// ... your code to send email ...
->setTo($emails)
// ...