论坛首页 编程语言技术论坛

phpmailer发邮件常见的一些问题总结

浏览 20966 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-04-14   最后修改:2009-04-16
PHP
    这几天做mail群发,碰到不少问题。一些常见的错误网上很多但没有答案,靠自己不断的尝试终于OK了~这里把几个常见的问题列出来做为工作笔记!
     要做发送邮件功能,首先要明白邮件收发的原理,引用网友一段话比较容易懂:
在Internet上将一段文本信息从一台计算机传送到另一台计算机上,可通过两种协议来完成,即SMTP(Simple Mail Transfer Protocol,简单邮件传输协议)和POP3(Post Office Protocol,邮局协议3)。SMTP是Internet协议集中的邮件标准。在Internet上能够接收电子邮件的服务器都有SMTP。电子邮件在发送前,发件方的SMTP服务器与接收方的SMTP服务器联系,确认接收方准备好了,则开始邮件传递;若没有准备好,发送服务器便会等待,并在一段时间后继续与接收方邮件服务器联系。这种方式在Internet上称为“存储——转发”方式。POP3可允许E-mail客户向某一SMTP服务器发送电子邮件,另外,也可以接收来自SMTP服务器的电子邮件。换句话说,电子邮件在客户PC机与服务提供商之间的传递是通过P0P3来完成的,而电子邮件在 Internet上的传递则是通过SMTP来实现。

  如果觉得不够清楚的话,则引用网上的一张图来解释吧:

  有关phpmailer的介绍可以参考官网:http://phpmailer.codeworxtech.com/
  常见异常:
  1.SMTP Error: Could not authenticate.
   这个是因为smtp验证没通过,就是smtp server 的用户名和密码不正确了
   
         $mail->Username   = "smtp@163.com";     // SMTP server username
	$mail->Password   = "******";  
    

    2.Could not execute: /usr/sbin/sendmail
    这是因为
   
      $mail->IsSendmail();  // tell the class to use Sendmail 
    

   去掉上面的代码就ok了!

3.关于phpmailer发送邮件产生中文乱码问题
  环境一:在普通环境,即标题内容等含中文的内容是在脚本中加上去的,或从文本中获取的,只需要进行如下操作(网上有很多):
   修改class.phpmailer.php中的EncodeHeader函数,改为:
 public function EncodeHeader($str, $position = 'text', $pl = 0) {
    $x = 0;
    if ($pl){return "=?".$this->CharSet."?B?".base64_encode($str)."?=";} 

再改下使用这个函数的一段:
if($this->Mailer != 'mail') {
      $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject),'text',1));
    }

   当然编码设置也不能少了:
 $mail->CharSet="utf-8"; 
        $mail->Encoding = "base64";

环境二:从excel中提取内容然后再发送excel中的内容给用户,这个折腾了我好久。最终找到解决办法了。最关键的地方是:excel中的编码是html格式的unicode,所以得使用下面这个函数将其转化为utf8,这个帖子的最后回复的人帮了我,谢谢他!帖子地址是:http://www.phpchina.com/bbs/viewthread.php?tid=111554
private function uc2html($str)
  {
    $ret = '';
    for( $i=0; $i<strlen($str)/2; $i++ )
    {
        $charcode = ord($str[$i*2])+256*ord($str[$i*2+1]);
        $ret .= '&#'.$charcode.';';
     }
    return mb_convert_encoding($ret,'UTF-8','HTML-ENTITIES');
  }
  


下面贴段测试代码:
  
<?php
/**
* Simple example script using PHPMailer with exceptions enabled
* @package phpmailer
* @version $Id$
*/

require '../class.phpmailer.php';

try {
	$mail = new PHPMailer(true); //New instance, with exceptions enabled

	$body             = file_get_contents('contents.html');
	$body             = preg_replace('/\\\\/','', $body); //Strip backslashes

	$mail->IsSMTP();                           // tell the class to use SMTP
	$mail->SMTPAuth   = true;                  // enable SMTP authentication
	$mail->Port       = 25;                // set the SMTP server port
	$mail->Host       = "smtp.xxxx.com"; // SMTP server
	$mail->Username   = "xxx@xxx.com";     // SMTP server username
	$mail->Password   = "xxxx";            // SMTP server password

	$mail->IsSendmail();  // tell the class to use Sendmail

	$mail->AddReplyTo("xxx@sina.com","xxxx");

	$mail->From       = "xxxx@m6699.com";
	$mail->FromName   = "DJB";

	$to = "xxx@sina.com";

	$mail->AddAddress($to);

	$mail->Subject  = "First PHPMailer Message";

	$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
	$mail->WordWrap   = 80; // set word wrap

	$mail->MsgHTML($body);

	$mail->IsHTML(true); // send as HTML

	$mail->Send();
	echo 'Message has been sent.';
} catch (phpmailerException $e) {
	echo $e->errorMessage();
}
?>
   


再给一个网上的操作excel的类,返回结果是一个数组。非常方便!用到的组件是PHP ExcelParser Pro v.4.2
<?php
/**
 * CopyRight (c) 2009,
 * All rights reserved.
 * 文件名:excel数据获取
 * 摘  要:
 *
 * @author 星期八 [email=ixqbar@hotmail.com]ixqbar@hotmail.com[/email]
 * @version 0.1
 */

class ExcelParser
{
    private $_data=array(0,'');
    private $_excel_handle;
    private $_excel=array();
    /**
     * 构造函数
     * @param <string> $filename 上传文件临时文件名称
     */
    public function __construct($filename)
    {
        /**
         * 引入excelparser类
         * 普通方法为
         * requires 路径.'excelparser.php';
         * import为ThinkPHP自带导入类方法
         */
         require("excelparser.php");
        $this->_excel_handle=new ExcelFileParser();
        //错误获取
        $this->checkErrors($filename);
    }
    /**
     * 错误校验
     */
    private function checkErrors($filename)
    {
        /**
         * 方法一
         */
        $error_code=$this->_excel_handle->ParseFromFile($filename);
        /**
         * 方法二
         * $file_handle = fopen($this->_filename,'rb');
         * $content = fread($file_handle,filesize($this->_filename));
         * fclose($file_handle);
         * $error_code = $this->_excel->ParseFromString($content);
         * unset($content,$file_handle);
         */
        switch($error_code)
        {
            case 0:
                //无错误不处理
                break;
            case 1:
                $this->_data=array(1,'文件读取错误(Linux注意读写权限)');
                break;
            case 2:
                $this->_data=array(1,'文件太小');
                break;
            case 3:
                $this->_data=array(1,'读取Excel表头失败');
                break;
            case 4:
                $this->_data=array(1,'文件读取错误');
                break;
            case 5:
                $this->_data=array(1,'文件可能为空');
                break;
            case 6:
                $this->_data=array(1,'文件不完整');
                break;
            case 7:
                $this->_data=array(1,'读取数据错误');
                break;
            case 8:
                $this->_data=array(1,'版本错误');
                break;
        }
        unset($error_code);
    }
    /**
     * Excel信息获取
     */
    private function getExcelInfo()
    {
        if(1==$this->_data[0])return;
        /**
         * 获得sheet数量
         * 获得sheet单元对应的行和列
         */
        $this->_excel['sheet_number']=count($this->_excel_handle->worksheet['name']);
        for($i=0;$i<$this->_excel['sheet_number'];$i++)
        {
            /**
             * 行于列
             * 注意:从0开始计数
             */
            $row=$this->_excel_handle->worksheet['data'][$i]['max_row'];
            $col=$this->_excel_handle->worksheet['data'][$i]['max_col'];
            $this->_excel['row_number'][$i]=($row==NULL)?0:++$row;
            $this->_excel['col_number'][$i]=($col==NULL)?0:++$col;
            unset($row,$col);
        }
    }
    /**
     * 中文处理函数
     * @return <string>
     */
  private function uc2html($str)
  {
    $ret = '';
    for( $i=0; $i<strlen($str)/2; $i++ )
    {
        $charcode = ord($str[$i*2])+256*ord($str[$i*2+1]);
        $ret .= '&#'.$charcode.';';
     }
    return mb_convert_encoding($ret,'UTF-8','HTML-ENTITIES');
   }
    /**
     * Excel数据获取
     */
    private function getExcelData()
    {
        if(1==$this->_data[0])return;

        //修改标记
        $this->_data[0]=1;
        //获取数据
        for($i=0;$i<$this->_excel['sheet_number'];$i++)
        {
            /**
             * 对行循环
             */
            for($j=0;$j<$this->_excel['row_number'][$i];$j++)
            {
                /**
                 * 对列循环
                 */
                for($k=0;$k<$this->_excel['col_number'][$i];$k++)
                {
                    /**
                     * array(4) {
                     *   ["type"]   => 类型 [0字符类型1整数2浮点数3日期]
                     *   ["font"]   => 字体
                     *   ["data"]   => 数据
                     *   ...
                     * }
                     */
                    $data=$this->_excel_handle->worksheet['data'][$i]['cell'][$j][$k];
                    switch($data['type'])
                    {
                        case 0:
                            //字符类型
                            if($this->_excel_handle->sst['unicode'][$data['data']])
                            {
                                //中文处理
                                $data['data'] = $this->uc2html($this->_excel_handle->sst['data'][$data['data']]);
                            }
                            else
                            {
                                $data['data'] = $this->_excel_handle->sst['data'][$data['data']];
                            }
                            break;
                        case 1:
                            //整数
                            //TODO
                            break;
                        case 2:
                            //浮点数
                            //TODO
                            break;
                        case 3:
                            //日期
                            //TODO
                            break;
                    }
                    $this->_data[1][$i][$j][$k]=$data['data'];
                    unset($data);
                }
            }
        }
    }
    /**
     * 主函数
     * @return <array> array(标识符,内容s)
     */
    public function main()
    {
        //Excel信息获取
        $this->getExcelInfo();
        //Excel数据获取
        $this->getExcelData();
        return $this->_data;
    }
}
   发表时间:2009-04-15  
有谁碰到phpmailer中文乱码问题么?
0 请登录后投票
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics