2015-04-12 273 views
1

我想通過我的Gmail賬戶發送郵件。Yii2 SwiftMailer通過遠程SMTP服務器發送郵件(gmail)

我的郵件配置:

[ 
'class' => 'yii\swiftmailer\Mailer', 
'useFileTransport' => false,//set this property to false to send mails to real email addresses 
'transport' => [ 
    'class' => 'Swift_SmtpTransport', 
    'host' => 'smtp.gmail.com', 
    'username' => '[email protected]', 
    'password' => 'pass', 
    'port' => '587', 
    'encryption' => 'tls', 
    ], 
] 

我寫命令MailController:

<?php 

namespace app\commands; 

use yii\console\Controller; 
use Yii; 

/** 
* Sanding mail 
* Class MailController 
* @package app\commands 
*/ 
class MailController extends Controller 
{ 
    private $from = '[email protected]'; 
    private $to = '[email protected]'; 

    public function actionIndex($type = 'test', $data = null) 
    { 
     Yii::$app->mailer->compose($type, ['data' => $data]) 
      ->setFrom($this->from) 
      ->setTo($this->to) 
      ->setSubject($this->subjects[$type]) 
      ->send(); 
    } 
} 

當我試圖運行:php yii mail

我得到:sh: 1: /usr/sbin/sendmail: not found

但爲什麼它需要sendmail,如果我只想SMTP連接smtp.gmail .COM?

+0

你確定這封郵件組件配置是關鍵「郵件」?根據這個配置,它甚至不應該嘗試發送電子郵件爲''useFileTransport'=> true「意味着它只保存消息到文件。 –

回答

6

我認爲你錯誤地配置了郵件程序。因爲它仍然使用默認的郵件功能。從documentation的配置應該如下所示。郵件應該在components之內。

'components' => [ 
    ... 
    'mailer' => [ 
     'class' => 'yii\swiftmailer\Mailer', 
     'transport' => [ 
      'class' => 'Swift_SmtpTransport', 
      'host' => 'smtp.gmail.com', 
      'username' => 'username', 
      'password' => 'password', 
      'port' => '587', 
      'encryption' => 'tls', 
     ], 
    ], 
    ... 
], 

還有一個建議是使用端口「465」和加密作爲「ssl」而不是端口「587」,加密「tls」。

+0

Ooops。我忘了命令有自己的配置文件,而不是web.php。現在郵件工作正常。 – ZeiZ

+2

@zeiz如果您找到解決方案,請將其作爲答案發布並接受。所以對別人會有所幫助。 –

2

Yii2具有不同的Web和控制檯作品的配置文件。所以你需要配置二者都。關於這個問題,我不得不作出(例如mailer.php)郵件配置文件,包括它在這兩個配置文件(web.php & console.php),如:

'components' => [ 
    ... 
    'mailer' => require(__DIR__ . '/mailer.php'), 
    ... 
], 
相關問題