Yii2中官方为了解决邮件发送问题,提供了swiftMailer
扩展。
安装
官方的包自带了yii2-swiftmailer
, 如果需要自行下载可以使用下面这个
1
| composer require --prefer-dist yiisoft/yii2-swiftmailer
|
配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| return [ 'components' => [ 'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', 'viewPath' => '@common/mail', 'useFileTransport' => false, 'transport' => [ 'class' => 'Swift_SmtpTransport', 'host' => 'smtp.163.com', 'username' => '******@163.com', 'password' => '******', 'port' => '25', 'encryption' => 'tls', ], 'messageConfig' => [ 'charset' => 'UTF-8', 'from' => ['***@163.com' => '白狼栈'] ], ], ], ];
|
简单使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <?php
namespace app\controllers;
use yii\web\Controller;
class EmailController extends Controller { public function actionEmail() { try { $result = \Yii::$app->mailer->compose() ->setFrom('******@163.com') ->setTo('******@163.com') ->setSubject('测试邮件') ->setTextBody('测试邮件') ->setHtmlBody('<b>测试邮件</b>') ->send(); } catch (\Exception $e) { var_dump($e->getMessage()); }
var_dump(1024);die; } }
|
批量发送
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public function actionEmailMulti() { $users = ['***@qq.com', '******@qq.com'];
$messages = []; foreach ($users as $user) { $messages[] = Yii::$app->mailer->compose() ->setTo($user) ->setSubject('测试主题') ->setHtmlBody('测试内容'); }
try { \Yii::$app->mailer->sendMultiple($messages); } catch (\Exception $e) { var_dump($e->getMessage()); }
var_dump(1024);die; }
|