【问题标题】:how to send mail using swiftmailer - Yii2如何使用 swiftmailer 发送邮件 - Yii2
【发布时间】:2017-01-09 12:38:18
【问题描述】:

我尝试在 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 的经理)发送电子邮件,以便在帖子发布到公众之前进行一些审核。谢谢。

【问题讨论】:

  • 您在配置 main.php 文件中正确配置了邮件组件吗?
  • 是的,我已经配置好了。如果我尝试了我的代码,它工作正常。但是,我需要从我的数据库表中的字段电子邮件中获取“setTo”。

标签: php yii2 swiftmailer


【解决方案1】:

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

您还可以提供一系列电子邮件地址 喜欢

->setTo(['email1@email.com', 'email1@email.com' => 'Name Surname'])

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

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

// or any condition you need in your application, this is just example
$users = User::find()->andWhere(['type' => 'approver'])->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)
// ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    相关资源
    最近更新 更多