- 主要使用swiftmailer,但由于Yii2.0会自带所以不用安装,只需配置下就可以了
- 接下来就是配置了 在components中进行如下配置,其中的SMTP密码需要在你自己的邮箱里去获取
'components' => [
//邮箱发送配置
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.qq.com',
'username' => '[email protected]',//发送者邮箱地址
'password' => 'tqxbygmfhpimbefa', //SMTP密码
'port' => '25',
'encryption' => 'tls',
],
'messageConfig'=>[
'charset'=>'UTF-8',
'from'=>['[email protected]'=>'system']
],
],
/.....
]
SMTP密码的获取
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI0gTMx81dsQWZ4lmZf1GLlpXazVmcvwFciV2dsQXYtJ3bm9CX9s2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xCMy81dvRWYoNHLwEzX5xCMx8FesU2cfdGLwMzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5iN1gTNykDNkRGOzQWZ0MDMzYzXxMTOzcTMyIzLchDMyIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.png)
/**
* 发送邮件
*
* @param string $from 发送邮箱
* @param string $to 收件邮箱
* @param string $subject 主题
* @param string $body 邮件内容,默认使用html
*
* @return bool
*/
public function actionIndex()
{
$from = Yii::$app->params['mail'];
$to = "[email protected]";
$subject = "早上好啊!";
$body = "You Are A Surper Man!";
$mailer = Yii::$app->mailer->compose();
$mailer->setFrom($from);
$mailer->setTo($to);
$mailer->setSubject($subject);
$mailer->setHtmlBody($body);
$status = $mailer->send();
echo $status;
}