今天在用yii2发送邮件的时候提示
Connection could not be established with host smtp.exmail.qq.com [ #0]
openssl没啥问题,函数权限也有打开了
折腾半天后终于找到解决办法
出问题之前的代码
/common/config/main-local.php中mailer配置
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
'useFileTransport' => false,//false发送邮件,true只是生成邮件在runtime文件夹下,不发邮件
'transport'=>[
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.exmail.qq.com',
'username' => '这里是公司的邮箱账号',
'password' => '邮箱密码',
'port' => '465',
'encryption' => 'ssl',
],
'messageConfig'=>[
'charset'=>'UTF-8',
'from'=>['这里是公司的邮箱账号'=>'Admin']
],
],
控制器中代码
$mail = Yii::$app->mailer->compose();
$mail->setTo('xingdong1117@126.com');
$mail->setSubject('测试邮件');
$mail->setHtmlBody('这里是内容'); //发布可以带html标签的文本
if ($mail->send()) {
echo "success";
}else {
echo "failse";
}
解决办法
在/common/config/main-local.php中mailer配置
'transport'=>[
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.exmail.qq.com',
'username' => '这里是公司的邮箱账号',
'password' => '邮箱密码',
'port' => '465',
'encryption' => 'ssl',
//这里是新加入的内容
'StreamOptions'=>[
'ssl'=>[
'verify_peer' => false, //是否需要验证 SSL 证书
'verify_peer_name'=>false,//Require verification of peer name.
'allow_self_signed' => true//是否允许自签名证书
],
]
],
//更多参数可以查看 http://php.net/manual/zh/context.ssl.php
其实在
在vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php 266行代码中
$streamContext = stream_context_create($options);
$this->_stream = @stream_socket_client($host.':'.$this->_params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $streamContext);
中间加入
$streamContext = stream_context_create($options);
//----
stream_context_set_option($streamContext, 'ssl', 'verify_peer',false);
stream_context_set_option($streamContext, 'ssl', 'verify_peer_name',false);
stream_context_set_option($streamContext, 'ssl', 'allow_self_signed',true);
//-----
$this->_stream = @stream_socket_client($host.':'.$this->_params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $streamContext);
也得到了解决,不过不如上面的办法
如果在使用phpmailer的时候也出现此问题,可以这样解决
<?php
$mail = new PHPMailer;
//$mail->SMTPDebug = 4;
$mail->isSMTP();
$mail->Host = 'smtp.exmail.qq.com';
$mail->SMTPAuth = true;
$mail->Username = '这里是公司的邮箱账号';
$mail->Password = '邮箱密码';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name'=>false,
'allow_self_signed' => true
)
);
$mail->setFrom('这里是公司的邮箱账号','Admin');
$mail->addAddress('xingdong1117@126.com');
$mail->addReplyTo('这里是公司的邮箱账号', 'Admin');
$mail->isHTML(true);
$mail->Subject = '测试邮件';
$mail->Body = '邮件内容';
if ($mail->send()) {
echo "success";
}else {
echo "failse";
}
ps:不知道啥原因导致的这样的情况,我本地是mac环境,没有这样的问题,到了linux服务器上就出现了这样的问题,只有加上这几个参数才可以。等找到真正原因再来写。
已有 0 条评论