yii 2 發送郵件方法

首先配置

'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
 'viewPath' => '@common/mail', //指定郵件模版路徑
            
 'useFileTransport' => false,//false:非測試狀態,發送真實郵件而非存儲爲文件
'transport'=>[ 'class' => 'Swift_SmtpTransport', 'host' =>'smtp.qq.com', //163-》smtp.163.com,qq->smtp.qq.com 'username' => '9***@qq.com', 'password' => '*****', //輸入的是客戶端的授權密碼而不是郵箱密碼 'port' => '465', 'encryption' => 'ssl',//ssl ], ],


在控制器中如下:

//發送郵件
	public function actionSendEmail(){
//		Yii::$app->mailer->compose()
//			->setFrom('****@163.com')
//			->setTo('****[email protected]')
//			->setSubject('這是測試的')
//			->setTextBody('這是測試的內容')
//			->send();
        //裏面參數代表指定模版和傳遞的參數  /mail/layouts/html裏面有模版了寫主體就行了
        Yii::$app->mailer->compose('email',['user'=>'張三'])
			->setFrom('****[email protected]')
			->setTo('*****@163.com')
			->setSubject('這是測試的')
			//->setTextBody('這是測試的內容')
			->send();
	}
模板:

<?php
use yii\helpers\Html;
use yii\helpers\Url;
 
 
/* @var $this \yii\web\View view component instance */
/* @var $message \yii\mail\BaseMessage instance of newly created mail message */
 
?>
<p>尊敬的:<b><?php echo $user; ?></b></p>
<h2><?php $url=Yii::$app->urlManager->createAbsoluteUrl(['site/reback','username'=>$user]); ?>
<p><a href="<?php echo $url; ?>"><?php echo $url; ?></a></p></h2>




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章