Yii2中发送邮件示例
{ Plan A. 服务器直接发送 }
{ Step 1. 配置 }
return [
//....
'components' => [
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
],
],
];
{ Step 2. 发送 }
$mailer = \Yii::$app->mailer->compose();
$mailer->setFrom($from);
$mailer->setTo($to);
$mailer->setSubject($subject);
$mailer->setTextBody($body);//text
$mailer->setHtmlBody($body);//html
$mailer->send();
{ Plan B. 使用第三方SMTP发送 }
以http://mail.163.com 为例
SMTP参数查看
163 : http://help.163.com/09/1221/08/5R1VKBKA00753VB9.html?servCode=6020378
Gmail : https://support.google.com/a/answer/176600
{ Step 1. 配置 }
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' =>false,//必填!! false表示发送邮件, true表示存在runtime文件包下
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.163.com', //SMTP config
'username' => 'Boy.Lee@163.com', //SMTP config
'password' => '*******',//SMTP config
'encryption' => 'tls', //SMTP config
'port' => '25', //SMTP config
],
'messageConfig'=>[
'charset'=>'UTF-8',
'from'=>['Boy.Lee@163.com'=>'Boy.Lee']
],
],
{ Step 2. 发送 }
$mailer = \Yii::$app->mailer->compose();
$mailer->setFrom($from);
$mailer->setTo($to);
$mailer->setSubject($subject);
$mailer->setTextBody($body);//text
$mailer->setHtmlBody($body);//html
$mailer->send();
{ Plan C. 使用第三方邮件服务商发送 }
以MailGun为例, 查看 YII 2.0 使用MAILGUN API 发送邮件
留言