Yii2邮件发送出现问题怎么解决

PHP中文网
发布: 2023-03-10 21:54:02
原创
1815 人浏览过

刚刚用了一下yii邮件发送功能,虽然结果返回成功,但接收不到邮件。配置文件代码如下:

'components' => [
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=yiidemo',
        'username' => 'root',
        'password' => 'root',
        'charset' => 'utf8',
    ],
    'mailer' => [
        'class' => 'yii\swiftmailer\Mailer',
        'viewPath' => '@common/mail',
        // send all mails to a file by default. You have to set
        // 'useFileTransport' to false and configure a transport
        // for the mailer to send real emails.
        'useFileTransport' => true,
        'transport' => [ 
            'class' => 'Swift_SmtpTransport', 
            'host' => 'smtp.qq.com', 
            'username' => '********@qq.com', 
            'password' => '********',
            'port' => '465', 
            'encryption' => 'ssl', 
        ], 
    ],
],
登录后复制

控制器代码:

public $modelClass = 'common\models\User';

public function actions()
{
    $actions = parent::actions();

    // 禁用"create" 操作后可用自己在控制器中写的方法
    unset($actions['update'],$actions['create'],$actions['delete']);
    
	//$actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
    return $actions;
}



public function actionCreate(){

	$request = Yii::$app->request;
	$params = $request->post();
	if($params){
		
		$fromName = $request->getBodyParam('fromName');
		$fromBady = $request->getBodyParam('fromBady');
		$toName = $request->getBodyParam('toName');
		$body = $request->getBodyParam('body');
		return $this->send($fromName,$fromBady,$toName,$body);
		
	}
	
	return false;

}

/*
 * Email Send function
 * @param1 $fromName
 * @param1 $toName
 * @param1 $body
 * $return boo1ean
 * 
 */

public function send($fromName,$fromBady,$toName,$body = ''){
	
	$mail = \Yii::$app->mailer->compose()
    	->setFrom([$fromName=>$fromBady])
   		->setTo($toName)
    	->setSubject('邮件发送配置')
    	->setTextBody($body)   //发布纯文字文本
    	->send();
    if($mail){
       	return [
            'name' => [
            	'fromName' => $fromName,
            	'fromBady' => $fromBady,
            	'toName' => $toName,
            	'body' => $body,
            ],
            'message' => '发生到['.$toName.']的邮件成功!',
            'code' => 0,
            'status' => 200,
    	];
    }else{
        return [
            'name' => 'Error',
            'message' => '发生到'.$toName.'的邮件失败!',
            'code' => 0,
            'status' => 402,
    	];
    }
}
登录后复制

但是你会发现数据返回是成功的但是你却没收到邮件

这是你应该把
'useFileTransport' => true 改成 'useFileTransport' => false,
并且你的邮箱密码是qq授权码(到你邮箱中的设置->账户 查看)

通过以上努力你会成功接收邮件!

以上是Yii2邮件发送出现问题怎么解决的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!