如何使用swiftmailer发送邮件 - Yii2

问题描述:

我试图使用swiftmailer在Yii2中发送电子邮件。我仍然是这个框架的初学者。这是我的基本代码:如何使用swiftmailer发送邮件 - Yii2

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; 
    } 

在我的情况,我想设置基于我usr表“setTo”。我usr表中的字段:

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

例如,当使用id = 1名的登录用户,然后他创建一个新的职位,并点击提交后,动作也发送电子邮件与ID用户= 2(法兹经理)在帖子发布之前进行一些评论。谢谢。

+1

所有电子邮件有你在你的配置main.php配置的邮件组件文件正确吗? – Chinmay

+0

是的,我配置了它。如果我尝试了我的代码,它工作正常。但是,我需要从我的数据库表中的字段电子邮件中获得'setTo'。 – Putra

注:我假设你usr表有模型称为User如果没有,那么将其更改为适合您的代码

可以提供同样的电子邮件的阵列不会忽略 像

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

要什么知道你想得到哪些用户,可能会添加一些条件主动记录等...

$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) 
// ...