Yii2 发送邮件

  1. 主要使用swiftmailer,但由于Yii2.0会自带所以不用安装,只需配置下就可以了
  2. 接下来就是配置了 在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密码的获取 Yii2 发送邮件

Yii2 发送邮件

Yii2 发送邮件

最后在控制器中发送邮件了

	 /**
     * 发送邮件
     * 
     * @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;
    }
	

如果输出1就代表发送成功了

第一次发布这个,排版有点问题,有不好的地方请大家多多指教,谢谢!

原文链接:https://www.yiichina.com/extension/1421