PHPMailer发送邮件报错Msg:stream_socket_enable_crypto():

 更新时间:2016年11月25日 17:00  点击:1517
今天在本机测试好的phpmailer邮箱发送功能没有问题,本地是windows apache php环境但在了linux中发送邮件就出现了Msg:stream_socket_enable_crypto(): this stream does not support SSL/crypto错误了,后来我分析了N久得出一办法,下面分享给各位朋友。


我的PHPMailer发送邮件代码

 代码如下 复制代码

header("Content-type:text/html;charset=utf-8");
include('phpmailer/class.phpmailer.php');
include('phpmailer/class.smtp.php');

$mail = new PHPMailer();  
 
$mail->IsSMTP();                                      // set mailer to use SMTP  
$mail->Host = "smtp.sohu.com";  // SMTP服务器  
$mail->Port = 25;
$mail->SMTPAuth = true;     // SMTP认证?  
$mail->Username = "yourmail@sohu.com";  // 用户名  
$mail->Password = "yourmail168"; // 密码  
$mail->From = "spr_zsql@163.com"; //发件人地址  
$mail->FromName = "test"; //发件人  
$mail->AddAddress("yourmail@qq.com", "test"); //收件人地址,收件人名称  
 
 
 
$mail->WordWrap = 50;                                 //   
//$mail->AddAttachment("/var/tmp/file.tar.gz");         // 附件  
//$mail->AddAttachment("/tmp/image.jpg", "new.jpg");    // 附件,新文件名  
$mail->IsHTML(true);                                  // HTML格式  
 
$mail->Subject    = "测试";
$mail->Body       = "测试";
              
if(!$mail->Send())
{
 echo "Mailer Error: " . $mail->ErrorInfo;
 echo "发送邮件错误!";
}else{
 echo "邮件发送成功!";
}


在使用PHPMailer发送邮件报错Msg:stream_socket_enable_crypto(): this stream does not support SSL/crypto,

出现这种情况请输出phpinfo()看下openssl这个扩展没有安装。

查找php安装时源码包的位置以/usr/local/src/php/php-5.3为例子

 代码如下 复制代码

cd  /usr/local/src/php/php-5.3/ext/openssl

/usr/local/php/bin/phpize

可能会出现下面的错误

 代码如下 复制代码
Cannot find config.m4.
Make sure that you run ‘/usr/local/php/bin/phpize’ in the top level source directory of the module

解决办法:

 代码如下 复制代码

mv config0.m4 config.m4
/usr/local/php/bin/phpize
./configure --with-openssl --with-php-config=/usr/local/php/bin/php-config
make && make install安装成功后会有以下提示
Build complete.
Don’t forget to run ‘make test’.

Installing shared extensions: /usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/

/usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/ 改目录下回生成一个openssl.so文件,找到php的配
置文件,在扩展区域添加

 代码如下 复制代码

extension=/usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/openssl.so
ps -ef | grep php-fpm  | grep -v grep | awk '{print $2}'|xargs kill -9
/usr/local/php/sbin/php-fpm

如果你配置了还不能发送邮箱我们可以尝试在linux中直接使用mail函数直接发送邮件哦。

今天在使用phpmailer发送邮件时居然提示SMTP Error: Could not authenticate,这个感觉是smtp设置的问题,下面我在网上找到了几种解决办法。

今天在使用phpmailer发送smtp邮件时提示 SMTP Error: Could not authenticate 错误,其中密码帐号都是正确的,邮箱也设置开启了SMTP功能。

上谷歌百度了一遍,有的说是服务器禁用了端口,有的说把class.phpmailer.php中的

 代码如下 复制代码

function IsSMTP() {
$this->Mailer = 'smtp';
}改为

function IsSMTP() {
$this->Mailer = 'SMTP';
}

测试以后还是不行,心中郁闷的一米。最后在一篇博客中找到了解决方法,先分享出来让更多遇到同样问题的人能得到帮助!


这个错误说明虚拟主机不支持PHPMailer默认调用的fsockopen函数,找到class.smtp.php文件,搜索fsockopen,就找到了这样一段代码:

 代码如下 复制代码

// connect to the smtp server
$this->smtp_conn = @fsockopen($host,// the host of the server
    $port,// the port to use
    $errno,   // error number if any
    $errstr,  // error message if any
    $tval);   // give up after ? secs

方法1:将fsockopen函数替换成pfsockopen函数

 
首先,在php.ini中去掉下面的两个分号

 
;extension=php_sockets.dll

 
;extension=php_openssl.dll

然后重启一下

因为pfsockopen的参数与fsockopen基本一致,所以只需要将@fsockopen替换成@pfsockopen就可以了。

方法2:使用stream_socket_client函数

一般fsockopen()被禁,pfsockopen也有可能被禁,所以这里介绍另一个函数stream_socket_client()。

stream_socket_client的参数与fsockopen有所不同,所以代码要修改为:

 代码如下 复制代码

$this->smtp_conn = stream_socket_client("tcp://".$host.":".$port, $errno,  $errstr,  $tval);

这样就可以了。


如果上面办法还是没有解决可能是邮箱自动过滤你机器自动登录邮箱发邮件了哦,我是使用下面办法解决的

刚开始使用的qq的帐号,提示上面错误。换成新注册的163帐号可以正常发送。


之后换了一个qq等级比较高的帐号,这下可以正常发送,没有报任何错误。

因为收件人用的是qq邮箱帐号,所以发件帐号用qq的邮箱比较好,这样发送过多不会轻易的被拦截或判为垃圾邮件。

所以结论就是配置中使用一个qq等级比较高的帐号(我的一个小号等级2个月亮可以正常使用,当然等级越高越好,)

ps:也要查看邮箱中“设置邮件地址黑名单”及“收信规则”,有时系统会自动将一些邮箱自动加入黑名单的

PHPMailer发送邮件现在php开发者比较常用的一个邮件发送组件了,利用它我们几乎不需要考虑任何问题,只要简单的把代码放网上把邮箱用户名密码与stmp改一下就可以发邮件了。

PHPMailer是别人封装好的一个发送邮件的库,用起来很方便。其支持mail、sendmail和smtp的方式可以到https://code.google.com/a/apache-extras.org/p/phpmailer/downloads/list去下载最新版本的。下面通过gmail smtp发送邮件为例来说明smtp使用方法。

 代码如下 复制代码


function sendMail($subject, $body, $to, $ccs = array()) {
    require_once './class.phpmailer.php';

    $mail  = new PHPMailer();
    //设定邮件编码,默认ISO-8859-1,也可以直接去源代码中修改
    $mail->CharSet = 'UTF-8';
    // 使用smtp的方式发送
    $mail->IsSMTP();
    //smtp服务器需要认证
    $mail->SMTPAuth = TRUE;
    //安全协议 gmail 是采用ssl的
    $mail->SMTPSecure = "ssl";
    //smtp服务器
    $mail->Host = 'smtp.gmail.com';
    //smtp服务器端口,普通是25
    $mail->Port = 465;
    //smtp 认证用户名和密码
    $mail->Username = 'yourgmailaccount@gmail.com';
    $mail->Password = "yourpassword";
    //发件人地址和名字,名字可以省略
    $mail->SetFrom('yourgmailaccount@gmail.com', 'display name');
    // 邮件标题
    $mail->Subject = $subject;
    // 邮件内容,支持HTML格式
    $mail->MsgHTML($body);
    // 收件人地址
    $mail->AddAddress($to);
    // 抄送人
    foreach ($ccs as $cc) {
        $mail->AddCC($cc);
    }

    if(!$mail->Send()) {
        echo "error info:" . $mail->ErrorInfo;
    }
}

上面是核心代码,下面我们综合一下实例。

按如下示例编写代码即可实现php在线发送邮件.
 

  一:前台表单

 代码如下 复制代码

<html>
<body>
<h3>phpmailer Unit Test</h3>
请你输入<font color="#FF6666">收信</font>的邮箱地址:
<form name="phpmailer" action="send.php" method="post">
<input type="hidden" name="submitted" value="1"/>
邮箱地址: <input type="text" size="50" name="address" />
<br/>
<input type="submit" value="发送"/>
</form>
</body>
</html>

 二:后台PHP程序

 代码如下 复制代码


 <?php
require("class.phpmailer.php"); //下载的文件必须放在该文件所在目录
$mail = new PHPMailer(); //建立邮件发送类
$address = $_POST['address'];
$mail->IsSMTP(); // 使用SMTP方式发送
$mail->Host = "mail.xxxxx.com"; // 您的企业邮局域名
$mail->SMTPAuth = true; // 启用SMTP验证功能
$mail->Username = "user@xxxx.com"; // 邮局用户名(请填写完整的email地址)
$mail->Password = "******"; // 邮局密码

$mail->From = "user@xxxx.com"; //邮件发送者email地址
$mail->FromName = "您的名称";
$mail->AddAddress("$address", "");//收件人地址,可以替换成任何想要接收邮件的email信箱,格式是AddAddress("收件人email","收件人姓名")
//$mail->AddReplyTo("", "");

//$mail->AddAttachment("/var/tmp/file.tar.gz"); // 添加附件
//$mail->IsHTML(true); // set email format to HTML //是否使用HTML格式

$mail->Subject = "PHPMailer测试邮件"; //邮件标题
$mail->Body = "Hello,这是测试邮件"; //邮件内容
$mail->AltBody = "This is the body in plain text for non-HTML mail clients"; //附加信息,可以省略

if(!$mail->Send())
{
 echo "邮件发送失败. <p>";
 echo "错误原因: " . $mail->ErrorInfo;
 exit;
}

echo "邮件发送成功";
?>

本文章来给各位同学详细介绍关于利用php中mail函数发送带有附件的邮件,有需要了解学习的朋友不防进入参考。

mail函数,发送邮件

语法: mail(to,subject,message,headers,parameters)

to 规定邮件的接收者
subject 规定邮件的主题。该参数不能包含任何换行字符
message 规定要发送的消息
headers 规定额外的报头,比如 From, Cc 以及 Bcc
parameters 规定 sendmail 程序的额外参数。
碰到的主要问题是乱码问题,刚开始是某些客户端接收邮件时好(比如QQ邮箱,估计带自动那个识别编码)的有些不foxmail、ipad显示乱码,解决方式正确的设置这个mail的headers就行了,下面是我使用的完美的无乱码的例子。


 在PHP中配置php.ini文件过程分为两个步骤:

1.先找到你放置所有PHP,Apache,MySQL文件的地方,在PHP文件夹里你可以发现有一个文件:php.ini,打开后,找到mail function地方,将原来的配置代码改为如下(仅对windows系统):

[mail function]
; For Win32 only.
SMTP =smtp.sohu.com   
mtp_port=25


; For Win32 only.
sendmail_from = 填上你的电子邮件全称。

   此处为以sohu的邮件服务器设置,如果你用163的邮箱,则设置为:smtp.163.com

2.在C盘搜索php.ini,选择不是快捷方式的那一个php.ini,应该在C/WINDOWS里面的,打开它,如上面一样修改它,保存。

设置完后,记得重启Apache服务器,然后mail()函数就可以用了。

 代码如下 复制代码

<?php
// 当发送 HTML 电子邮件时,请始终设置 content-type
$headers = "MIME-Version: 1.0" . "rn";

$headers .= "Content-type:text/html; charset=utf-8";

mail($to,$subject,$message,$headers);
?>

上面函数不可以带附件了,下面我们升级一下

 

 代码如下 复制代码

<?php

class Mail {
private $topic;
private $toaddr;
private $fromaddr;
private $cc;
private $content;
private $attach;
private $header;
private $domain;//邮箱域
private $msg;

private $filename;
private $filemime;
private $filestr;

private $boundary;
private $uniqid;

private $eol; //每行末尾所加的换行符类型


function __construct(){
$this->getEOT();//生成结尾换行符
$this->getUniq_id();
$this->header='';
$this->attach='';
$this->cc='';
$this->msg='';


}


public function getFromaddr() {
return $this->fromaddr;
}

public function setFromaddr($fromaddr) {
$this->fromaddr = $fromaddr;
}

public function getTopic() {
return $this->topic;
}


public function getToaddr() {
return $this->toaddr;
}


public function getCc() {
return $this->cc;
}

public function getContent() {
return $this->content;
}


public function getAttach() {
return $this->attach;
}


public function setTopic($topic) {
$this->topic = mb_convert_encoding(trim($topic),'UTF-8','auto');
}

public function setToaddr($toaddr) {
$this->toaddr = trim($toaddr);
}


public function setCc($cc) {
$this->cc = trim($cc);
}


public function setContent($content) {
$this->content = mb_convert_encoding(trim($content),'UTF-8','auto');
}


public function setAttach($attach) {
$this->attach = trim($attach);
}

public function getDomain() {
return $this->domain;
}

public function setDomain($domain) {
$this->domain = $domain;//输入的值为'@domain.com'
}


/*
* 根据系统类型设置换行符
*/
private function getEOT() {
if (strtoupper ( substr ( PHP_OS, 0, 3 ) == 'WIN' )) {
$this->eol = "rn";
} elseif (strtoupper ( substr ( PHP_OS, 0, 3 ) == 'MAC' )) {
$this->eol= "r";
} else {
$this->eol = "n";
}
}


private function getBoundary(){

$this->boundary= '--'.substr(md5(time().rand(1000,2000)),0,16);

}

private function getUniq_id(){

$this->uniqid= md5(microtime().time().rand(1,100));

}

private function outputCommonHeader(){
$this->header .= 'From: '.$this->fromaddr.$this->eol;
//$this->header .= 'To: '.$this->toaddr.$this->eol;
//$this->header .= 'Subject: '.$this->topic.$this->eol;
$this->header .= 'Message-ID: <'.$this->uniqid.$this->domain.'>'.$this->eol;
$this->header .= 'MIME-Version: 1.0'.$this->eol;
$this->header .= 'Reply-To: '.$this->fromaddr.$this->eol;
$this->header .= 'Return-Path: '.$this->fromaddr.$this->eol;
$this->header .= 'X-Mailer: Xmail System'.$this->eol;
$this->header .= 'Content-Disposition: inline'.$this->eol;
}

private function mime_content_type ( $f )
{
$temp = trim ( exec ('file -bi ' . escapeshellarg ( $f ) ) ) ;
$temp = preg_replace('/s+/',' ',$temp);
$temp = explode(' ',$temp);
return $temp[0];
}//判断文件的mime类型


/*
* 只带有抄送
*/
private function mailWithCC(){
$this->header .= 'Cc: '.$this->cc.$this->eol;
$this->header .= 'Content-type: text/html; charset=UTF-8'.$this->eol;
$this->header .= 'Content-Transfer-Encoding: 8bit'.$this->eol;
$this->msg = $this->content;
if(mail($this->toaddr,$this->topic,$this->msg,$this->header)){

return 1;
}else{
return 0;
}
}
/*
* $filedir需要是绝对地址
*/
private function attachmentToBase64($filedir){
$this->filename = basename($filedir);
@$fopen = fopen($filedir,'r');
$str = fread($fopen,filesize($filedir));
$str = base64_encode($str);
$this->filestr = $str;
}


/*
* 只带有附件
*/
private function mailWithAttach(){
$this->attachmentToBase64($this->attach);
$this->header .= 'Content-type: multipart/mixed; boundary="'.str_replace('--','',$this->boundary).'"'.$this->eol;
$this->msg .= $this->eol.$this->boundary.$this->eol;
$this->msg .= 'Content-Type: text/html; charset=utf-8'.$this->eol;
$this->msg .= 'Content-Disposition: inline'.$this->eol;
$this->msg .= $this->eol.$this->content.$this->eol;
$this->msg .= $this->boundary.$this->eol;
$this->msg .= 'Content-Type: '.$this->mime_content_type($this->attach).$this->eol;
$this->msg .= 'Content-Disposition: attachment; filename="'.$this->filename.'"'.$this->eol;
$this->msg .= 'Content-Transfer-Encoding: base64'.$this->eol;
$this->msg .= $this->eol.$this->filestr.$this->eol;
$this->msg .= $this->eol.$this->boundary.'--';

if(mail($this->toaddr,$this->topic,$this->msg,$this->header)){

return 1;
}else{
return 0;
}
}

/*
* 带有附件和抄送
*/
private function mailAll(){

$this->attachmentToBase64($this->attach);
$this->header .= 'Cc: '.$this->cc.$this->eol;
$this->header .= 'Content-type: multipart/mixed; boundary="'.str_replace('--','',$this->boundary).'"'.$this->eol;
$this->msg .= $this->eol.$this->boundary.$this->eol;
$this->msg .= 'Content-Type: text/html; charset=utf-8'.$this->eol;
$this->msg .= 'Content-Disposition: inline'.$this->eol;
$this->msg .= $this->eol.$this->content.$this->eol;
$this->msg .= $this->boundary.$this->eol;
$this->msg .= 'Content-Type: '.$this->mime_content_type($this->attach).$this->eol;
$this->msg .= 'Content-Disposition: attachment; filename="'.$this->filename.'"'.$this->eol;
$this->msg .= 'Content-Transfer-Encoding: base64'.$this->eol;
$this->msg .= $this->eol.$this->filestr.$this->eol;
$this->msg .= $this->eol.$this->boundary.'--';

if(mail($this->toaddr,$this->topic,$this->msg,$this->header)){

return 1;
}else{
return 0;
}

}
/*
* 不带抄送和附件
*/
private function mailSimple(){
$this->header .= 'Content-type: text/html; charset=UTF-8'.$this->eol;
$this->header .= 'Content-Transfer-Encoding: 8bit'.$this->eol;
$this->msg = $this->content;
if(mail($this->toaddr,$this->topic,$this->msg,$this->header)){

return 1;
}else{
return 0;
}
}

public function send(){

if(empty($this->attach)&&empty($this->cc)){
$this->outputCommonHeader();
return $this->mailSimple();

}else if(empty($this->attach)){
$this->outputCommonHeader();
return $this->mailWithCC();

}else if(empty($this->cc)){
$this->outputCommonHeader();
$this->getBoundary(); //有附件就生成boundary
return $this->mailWithAttach();

}else if(!empty($this->toaddr)&&!empty($this->topic)&&!empty($this->cc)&&!empty($this->content)&&!empty($this->attach)){
$this->outputCommonHeader();
$this->getBoundary(); //有附件就生成boundary
return $this->mailAll();
}
}
}


示例代码,有些变量需要上下文环境:

 代码如下 复制代码

$m = new Mail();
$m->setToaddr($this->temp['receipt_address']);
$m->setTopic($this->temp['mail_title']);
$m->setContent($this->temp['mail_content']);
$m->setFromaddr($_SESSION['user']['name'].' <'.$_SESSION['user']['name'].'@'.SystemDomain.'>');
$m->setDomain('@'.SystemDomain);
$m->setCc($this->temp['cc_address']);
$m->setAttach(PATH.'/temp/'.$this->temp['attachment_file']);
$m->send();


优点:使用方便就一个简单的函数
缺点:需要php.ini支持该函数,如果某些服务器不支持而又不能改环境那就不行了而且总是不稳定,发的有时能收到有时不能

phpmailer发送邮件是php开发者首选的一个邮件发送插件了,下面我来介绍怎么集成phpmailer到thinkphp框架了,有需要了解的朋友可参考。


phpmailer发送邮件功能很强大,今天真正的体验一下,简单说一下配置,本人是在thinkphp中是用的

配置步骤:

1.后台配置发送邮件类,位置admin/common/common.php

 代码如下 复制代码

function sendmail($tomail,$title,$content)
{

/*邮件设置信息*/
        $email_set = C('EMAIL_SET');

        Vendor('phpmailer.class#phpmailer');
        Vendor("phpmailer.class#smtp"); //可选,否则会在class.phpmailer.php中包含
       
        $mail = new PHPMailer(true); //实例化PHPMailer类,true表示出现错误时抛出异常
       
        $mail->IsSMTP(); // 使用SMTP

          $mail->CharSet ="UTF-8";//设定邮件编码
          $mail->Host       = $email_set['Host']; // SMTP server
          $mail->SMTPDebug  = 1;                     // 启用SMTP调试 1 = errors  2 =  messages
          $mail->SMTPAuth   = true;                  // 服务器需要验证
          $mail->Port       = $email_set['port'];                    // 设置端口
         // $mail->SMTPSecure = "ssl";    
            /*
            $mail->SMTPSecure = "ssl";                
            $mail->Host       = "smtp.gmail.com";    
            $mail->Port       = 465;                 
            */
       
          $mail->Username   = $email_set['email_user']; //SMTP服务器的用户帐号
          $mail->Password   = $email_set['email_pwd'];       //SMTP服务器的用户密码
          $mail->AddReplyTo($email_set['email'],$email_set['email_name']); //收件人回复时回复到此邮箱,可以多次执行该方法
          if (is_array($tomail)){
              foreach ($tomail as $m){
                   $mail->AddAddress($m, 'user');
              }
          }else{
              $mail->AddAddress($tomail, 'user');
          }
        
          $mail->SetFrom($email_set['email'],$email_set['email_name']);
        // $mail->AddAttachment('./img/phpmailer.gif');      // 添加附件,如果有多个附件则重复执行该方法
          $mail->Subject = $title;
       
          //以下是邮件内容相关
          $mail->Body = $content;
          $mail->IsHTML(true);
       
          //$body = file_get_contents('tpl.html'); //获取html网页内容
         // $mail->MsgHTML(eregi_replace("[]",'',$body));
       
       
        return $mail->Send()? true:false;

2:配置文件中配置参数:

 代码如下 复制代码

/*邮件设置*/
    'EMAIL_SET'=>array(
       'Host'=> "smtp.163.com",
       'Port'=>'25',
       'email_user'=>'liuying',
       'email_pwd'=>'123456',
       'email'=>'liuying@163.com',
       'email_name'=>'86市场网',
    ),

3.测试发送代码:

 代码如下 复制代码

sendmail(’11234@126.com‘,‘您好’,‘我是内容’);

[!--infotagslink--]

相关文章