1.在配置文件中(main-local.php),添加下列代码(注意是放到 components 参数里):
<?php
return [
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii1',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' =>false,//这句一定有,false发送邮件,true只是生成邮件在runtime文件夹下,不发邮件
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.163.com', //每种邮箱的host配置不一样
'username' => 'xxxxxxx@163.com', // 邮箱账号
'password' => 'aaaaa', // 邮箱密码(授权密码)
'port' => '25',
'encryption' => 'tls',
],
'messageConfig'=>[
'charset'=>'UTF-8',
'from'=>['xxxxxxxx@163.com'=>'admin']
],
],
],
];
2.控制器中调用
$mail= Yii::$app->mailer->compose();
$mail->setTo('1414935835@qq.com');
$mail->setSubject("邮件测试");
//$mail->setTextBody('zheshisha '); //发布纯文字文本
$mail->setHtmlBody("<br>问我我我我我"); //发布可以带html标签的文本
if($mail->send())
echo "发送成功";
else
echo "发送失败";
die();