Php 如何使用swiftmailer-Yii2发送邮件

Php 如何使用swiftmailer-Yii2发送邮件,php,yii2,swiftmailer,Php,Yii2,Swiftmailer,我尝试在Yii2中使用swiftmailer发送电子邮件。我还是这个框架的初学者。这是我的基本代码: public function sendMail($email) { if ($this->validate()) { $email = Yii::$app->params['adminEmail']; $mailto = 'user@gmail.com'; // need to change

我尝试在Yii2中使用swiftmailer发送电子邮件。我还是这个框架的初学者。这是我的基本代码:

public function sendMail($email)
    {
        if ($this->validate()) {
            $email = Yii::$app->params['adminEmail'];
            $mailto = 'user@gmail.com'; // 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;
    }
在我的例子中,我想根据我的
usr
表设置一个“setTo”。我的
usr
表格的字段:

id | username | manager | email           | type     |
1  | fauzi    | arie    | fauzi@gmail.com | user     |
2  | arie     | rian    | arie@gmail.com  | approver |

例如,当id=1的用户登录时,他将创建一篇新文章,并在单击“提交”后,该操作还会向id=2的用户(fauzi的经理)发送电子邮件,以便在将文章发布到公众之前进行审查。谢谢。

注意:我假设您的
usr
表具有名为
User
的模型,如果没有,请将其更改为适合您的代码

您还可以提供电子邮件地址数组 像

你想知道的是你想得到哪些用户,也许可以给activerecord添加一些条件等等

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

然后
Variant#1
您可以在所有记录中循环

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)
}
或者
Variant#2
您可以先收到所有电子邮件

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

您是否在config main.php文件中正确配置了mailer组件?是的,我已经配置好了。如果我尝试我的代码,它工作正常。但是,我需要从数据库表中的字段电子邮件中获取“setTo”。
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)
}
$emails = \yii\helpers\ArrayHelper::getColumn($users, 'email');
// ... your code to send email ...
->setTo($emails)
// ...