Yii2 之邮件发送

时间:2022-09-24 08:42:44

1 如果没有安装

php composer.phar require --prefer-dist yiisoft/yii2-swiftmailer

2 在配置文件main-local.php components=>[]里面配置

'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
'useFileTransport' => false, //这句必须要有,否则不会发送
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.163.com',
'username' => 'ahcj_11@163.com',
'password' => '密码****',
'port' => '25',
'encryption' => 'tls',
],

'messageConfig'=>[
'charset'=>'UTF-8',
'from'=>['ahcj_11@163.com'=>'admin']
],
],

3 新建 测试 控制器

<?php
namespace frontend\controllers;

use Yii;
use yii\web\Controller;

class TestController extends Controller
{

public function actionSend()
{

$mail = Yii::$app->mailer->compose();
$mail->setTo('ahcj_11@163.com');
$mail->setSubject('邮件的标题');
$mail->setHtmlBody('邮件内容,这里可以使用 HTML 代码');

echo $mail->send() ? "success":"failse";
}

}

在浏览器访问控制器
Yii2 之邮件发送

4 使用邮件模板 resetPasword.php
模板代码放在 ‘viewPath’ => ‘@common/mail’, 指定的目录

<?php
use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $user common\models\User */

$resetLink = Yii::$app->urlManager->createAbsoluteUrl(['test/reset-password', 'token' => $user->password_reset_token]);
?>

<div class="password-reset">
<p><?= Html::encode($param1) ?>,</p>

<p>这是一个模板测试 -- Follow the link below to reset your password:</p>

<p><?= Html::a(Html::encode($resetLink), $resetLink) ?></p>
</div>

Action

public function actionSendReset(){
$mail= Yii::$app->mailer->compose('resetPasword',['param1'=>'找回密码']);
$mail->setTo('ahcj_11@163.com');
$mail->setSubject("找回密码");
$mail->setTextBody('找回密码 ');
echo $mail->send() ? "success":"failse";
}

Yii2 之邮件发送

5 使用layout,布局文件这里放到 @common/mail/layouts 目录下面。

Yii::$app->mailer->compose('test', [ 
'html' => 'layout1Html',
'parm1' => '找回密码'
]) ->setTo('ahcj_11@163.com')
->
setSubject('找回密码')
->
send();

6 发送附件

$message = Yii::$app->mailer->compose(); 
$message->attach('http://f.hiphotos.baidu.com/image/h%3D200/sign=3d746172a4efce1bf52bcfca9f50f3e8/bba1cd11728b47101489df48c0cec3fdfd03238b.jpg');
$message->attachContent('Attachment content', ['fileName' => '/tmp/test.txt', 'contentType' => 'text/plain']);
$message->setTo('ahcj_11@163.com');
$message->setSubject('附件测试');
$message->send();

结果如图
Yii2 之邮件发送

7 动态设置 mail 配置信息

$mail = Yii::$app->mailer;
$mail->transport = $mail->transport->newInstance($host, $port, 'tls');
$mail->transport->setUsername('你的邮箱帐号');
$mail->transport->setPassword('你的邮箱密码');

8 批量发送邮件

$users = ['abc@abc', '123@abc']; 
$messages = [];
foreach ($users as $user) {
$messages[] = Yii::$app->mailer->compose()
->setTo($user)
->setSubject('测试主题')
->setHtmlBody('测试内容');
}
Yii::$app->mailer->sendMultiple($messages);