2017-01-09 50 views
2

我試圖使用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

回答

0

注:我假設你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) 
// ... 
相關問題