原文:http://yiilib.com/topic/675/Yii2%E4%B8%AD%E5%8F%91%E9%80%81%E9%82%AE%E4%BB%B6%E7%A4%BA%E4%BE%8B
{ Plan A. 服务器直接发送 }
{ Step 1. 配置 }
1 return [ 2 //.... 3 'components' => [ 4 'mailer' => [ 5 'class' => 'yii\swiftmailer\Mailer', 6 ], 7 ], 8 ];
{ Step 2. 发送 }
1 $mailer = \Yii::$app->mailer->compose(); 2 $mailer->setFrom($from); 3 $mailer->setTo($to); 4 $mailer->setSubject($subject); 5 $mailer->setTextBody($body);//text 6 $mailer->setHtmlBody($body);//html 7 $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. 配置 }
1 'mailer' => [ 2 3 'class' => 'yii\swiftmailer\Mailer', 4 'useFileTransport' =>false,//必填!! false表示发送邮件, true表示存在runtime文件包下 5 6 'transport' => [ 7 'class' => 'Swift_SmtpTransport', 8 'host' => 'smtp.163.com', //SMTP config 9 'username' => 'Boy.Lee@163.com', //SMTP config 10 'password' => '*******',//SMTP config 11 'encryption' => 'tls', //SMTP config 12 'port' => '25', //SMTP config 13 14 ], 15 16 'messageConfig'=>[ 17 'charset'=>'UTF-8', 18 'from'=>['Boy.Lee@163.com'=>'Boy.Lee'] 19 ], 20 ],
{ Step 2. 发送 }
1 $mailer = \Yii::$app->mailer->compose(); 2 $mailer->setFrom($from); 3 $mailer->setTo($to); 4 $mailer->setSubject($subject); 5 $mailer->setTextBody($body);//text 6 $mailer->setHtmlBody($body);//html 7 $mailer->send();
{ Plan C. 使用第三方邮件服务商发送 }
以MailGun为例, 查看 YII 2.0 使用MAILGUN API 发送邮件