Yii2 邮件发送

Yii2中官方为了解决邮件发送问题,提供了swiftMailer扩展。

安装

官方的包自带了yii2-swiftmailer, 如果需要自行下载可以使用下面这个

1
composer require --prefer-dist yiisoft/yii2-swiftmailer

配置

  • config/web.php
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',
// 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.
'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' => '******@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;
}

Powered by Hexo and Hexo-theme-hiker

Copyright © 2017 - 2022 Keep It Simple And Stupid All Rights Reserved.

访客数 : | 访问量 :