參照於 http://www.manks.top/yii2_swi...
直接上代碼
1、配置文件web.phpphp
'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', 'viewPath' => 'xx/mail', //根據實際狀況配置 'useFileTransport' => false, 'transport' => [ //這裏若是你是qq的郵箱,能夠參考qq客戶端設置後再進行配置 http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256 'class' => 'Swift_SmtpTransport', 'host' => 'smtp.163.com', 'username' => 'XXX@163.com', //改爲本身的用戶名密碼 'password' => 'XXX', 'port' => '994', //或者25端口 'encryption' => 'ssl', //或者tls ], 'messageConfig'=>[ 'charset'=>'UTF-8', 'from'=>['XXX@163.com'=>'發送人的名字'] ], ],
2、基礎用法html
public function actionSend(){ $mail= Yii::$app->mailer->compose(); $mail->setTo('XXX@qq.com'); //要發送給那我的的郵箱 $mail->setSubject("郵件主題"); //郵件主題 $mail->setTextBody('測試text'); //發佈純文字文本 $mail->setHtmlBody("測試html"); //發送的消息內容 var_dump($mail->send()); }
3、發送多個郵件web
public function actionSendmult(){ $users = ['XXX@163.com','XXX@qq.com']; foreach($users as $user) { $messages[] = Yii::$app->mailer->compose() ->setTo($user) ->setSubject('測試主題') ->setHtmlBody('<h1>測試多郵件</h1>'); } $res = Yii::$app->mailer->sendMultiple($messages); if ($res){ echo 'success'; } }
4、發送郵件用模板swift
controller代碼: public function actionSendtem(){ $res = Yii::$app->mailer->compose('welcome', [ 'html' => 'html', //key固定,value是模版文件名,佈局文件在mail\layouts目錄下面 'title' => '郵件' ,//傳遞的參數 ]) ->setTo('XXX@qq.com') ->setSubject('Message subject') ->send(); var_dump($res); //true } welcome.php文件: <h2><?= $title ?></h2>
5、發送文件和圖片yii2
public function actionFile(){ $message = Yii::$app->mailer->compose(); $message->attach('img/2.png'); //可訪問的圖片地址或者文件 $message->attachContent('文件內容', ['fileName' => '1.txt', 'contentType' => 'text/plain']); $message->setTo('XXX@qq.com'); $message->setSubject('Message subject'); $res = $message->send(); if ($res){ echo 'success'; } }
6、內容鑲嵌圖片app
//controller Yii::$app->mailer->compose('welcome', [ 'title' => '嵌入圖片', 'imageFileName' => '圖片可訪問地址' ]) ->setTo('***@163.com') ->setSubject('Message subject') ->send(); //welcome.php <img src="<?= $message->embed($imageFileName); ?>"> //或者這裏直接寫圖片的可訪問地址,不用embed方法。