使用PHPMailer发送邮件实例代码总结

 更新时间:2016年11月25日 17:00  点击:2190
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 "邮件发送成功";
?>

今天在本机测试好的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函数直接发送邮件哦。

本文章来给各位同学详细介绍关于利用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‘,‘您好’,‘我是内容’);

我想使用邮件接收类的朋友可能比较少,但是发送邮件的类使用的朋友比较多啊,下面我来分别给大家介绍PHP邮件接收与发送类实现程序详解,希望对大家所有帮助哦。

主要的改进如下:

1、新增了listMessages方法,用于列表邮件列表,且带有分页功能,更加方便调用

/**
 * listMessages - 获取邮件列表
 * @param $page - 第几页
 * @param $per_page - 每页显示多少封邮件
 * @param $sort - 邮件排序,如:array('by' => 'date', 'direction' => 'desc')
 * */
function listMessages($page = 1, $per_page = 25, $sort = null){}


2、新增了两个编码转换的方法,主要用于对邮件的相关信息进行编码转换。

调用方法如下:

 代码如下 复制代码

include("receivemail.class.php");
$obj = receiveMail('abc@abc.com','xxxxxx','abc@abc.com','pop.abc.com','pop3','110', false);
$obj->connect();
$maillist = $obj->listMessages();
print_r($maillist);

运行结果大致如下:

Array
(
    [res] => Array
        (
         [0] => stdClass Object
          (
           [subject] => 解决PHP邮件接收类的乱码问题
           [from] => xxx <xxx@phper.org.cn>
           [to] => abc <abc@abc.com>
           [date] => Mon, 28 Jan 2013 14:23:06 +0800 (CST)
           [message_id] => <2afc51061915f95-00004.Richmail.00037000523146269922@xxx.com>
                    [size] => 42259
                    [uid] => 1
                    [msgno] => 1
                    [recent] => 1
                    [flagged] => 0
                    [answered] => 0
                    [deleted] => 0
                    [seen] => 0
                    [draft] => 0
                    [body] => 邮件内容
          )
        )
 [start] => 1
    [limit] => 25
    [sorting] => Array
        (
            [by] =>
            [direction] =>
        )

    [total] => 47
    [pages] => 2
)


 

receivemail.class.php类文件

 代码如下 复制代码

<?php
class receiveMail
{
 var $server='';
 var $username='';
 var $password='';
 
 var $marubox='';     
 
 var $email='';   
 
 function receiveMail($username,$password,$EmailAddress,$mailserver='localhost',$servertype='pop',$port='110',$ssl = false) //Constructure
 {
  if($servertype=='imap')
  {
   if($port=='') $port='143';
   $strConnect='{'.$mailserver.':'.$port. '}INBOX';
  }
  else
  {
   $strConnect='{'.$mailserver.':'.$port. '/pop3'.($ssl ? "/ssl" : "").'}INBOX';
  }
  $this->server   = $strConnect;
  $this->username   = $username;
  $this->password   = $password;
  $this->email   = $EmailAddress;
 }
 
 function connect() //Connect To the Mail Box
 {
  $this->marubox=@imap_open($this->server,$this->username,$this->password);
  
  if(!$this->marubox)
  {
   echo "Error: Connecting to mail server";
   exit;
  }
 }
 
 function listMessages($page = 1, $per_page = 25, $sort = null)
  {
       $limit = ($per_page * $page);
       $start = ($limit - $per_page) + 1;
       $start = ($start < 1) ? 1 : $start;
       $limit = (($limit - $start) != ($per_page-1)) ? ($start + ($per_page-1)) : $limit;
       $info = imap_check($this->marubox);
       $limit = ($info->Nmsgs < $limit) ? $info->Nmsgs : $limit;
 
       if(true === is_array($sort))
       {
           $sorting = array(
               'direction' => array( 'asc' => 0, 'desc' => 1),
               'by'        => array('date' => SORTDATE, 'arrival' => SORTARRIVAL,
                                   'from' => SORTFROM, 'subject' => SORTSUBJECT, 'size' => SORTSIZE));
           $by = (true === is_int($by = $sorting['by'][$sort[0]])) ? $by : $sorting['by']['date'];
           $direction = (true === is_int($direction = $sorting['direction'][$sort[1]])) ? $direction : $sorting['direction']['desc'];
           $sorted = imap_sort($this->marubox, $by, $direction);
           $msgs = array_chunk($sorted, $per_page);
           $msgs = $msgs[$page-1];
       }
       else
       {
           $msgs = range($start, $limit); //just to keep it consistent
       }
       $result = imap_fetch_overview($this->marubox, implode($msgs, ','), 0);
       if(false === is_array($result)) return false;
 
       foreach ($result as $k => $r)
       {
         $result[$k]->subject = $this->_imap_utf8($r->subject);
         $result[$k]->from = $this->_imap_utf8($r->from);
         $result[$k]->to = $this->_imap_utf8($r->to);
   $result[$k]->body = $this->getBody($r->msgno);
       }
       //sorting!
       if(true === is_array($sorted))
       {
           $tmp_result = array();
           foreach($result as $r)
           {
             $tmp_result[$r->msgno] = $r;
           }
 
           $result = array();
           foreach($msgs as $msgno)
           {
    $result[] = $tmp_result[$msgno];
           }
       }
 
       $return = array('res' => $result,
                       'start' => $start,
                       'limit' => $limit,
                       'sorting' => array('by' => $sort[0], 'direction' => $sort[1]),
                       'total' => imap_num_msg($this->marubox));
       $return['pages'] = ceil($return['total'] / $per_page);
       return $return;
   }
 
 function getHeaders($mid) // Get Header info
 {
  if(!$this->marubox)
   return false;

  $mail_header=imap_header($this->marubox,$mid);
  $sender=$mail_header->from[0];
  $sender_replyto=$mail_header->reply_to[0];
  if(strtolower($sender->mailbox)!='mailer-daemon' && strtolower($sender->mailbox)!='postmaster')
  {
   $mail_details=array(
     'from'=>strtolower($sender->mailbox).'@'.$sender->host,
     'fromName'=>$sender->personal,
     'toOth'=>strtolower($sender_replyto->mailbox).'@'.$sender_replyto->host,
     'toNameOth'=>$sender_replyto->personal,
     'subject'=>$mail_header->subject,
     'to'=>strtolower($mail_header->toaddress)
    );
  }
  return $mail_details;
 }
 
 function get_mime_type(&$structure) //Get Mime type Internal Private Use
 {
  $primary_mime_type = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");
  
  if($structure->subtype) {
   return $primary_mime_type[(int) $structure->type] . '/' . $structure->subtype;
  }
  return "TEXT/PLAIN";
 }
 
 function get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false) //Get Part Of Message Internal Private Use
 {
  if(!$structure) {
   $structure = imap_fetchstructure($stream, $msg_number);
  }
  if($structure) {
   if($mime_type == $this->get_mime_type($structure))
   {
    if(!$part_number)
    {
     $part_number = "1";
    }
    $text = imap_fetchbody($stream, $msg_number, $part_number);
    if($structure->encoding == 3)
    {
     return imap_base64($text);
    }
    else if($structure->encoding == 4)
    {
     return imap_qprint($text);
    }
    else
    {
     return $text;
    }
   }
   if($structure->type == 1) /* multipart */
   {
    while(list($index, $sub_structure) = each($structure->parts))
    {
     if($part_number)
     {
      $prefix = $part_number . '.';
     }
     $data = $this->get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1));
     if($data)
     {
      return $data;
     }
    }
   }
  }
  return false;
 }
 
 function getTotalMails() //Get Total Number off Unread Email In Mailbox
 {
  if(!$this->marubox)
   return false;

  $headers=imap_headers($this->marubox);
  return count($headers);
 }

 function GetAttach($mid,$path) // Get Atteced File from Mail
 {
  if(!$this->marubox)
  {
   return false;
  }

  $struckture = imap_fetchstructure($this->marubox,$mid);
  $ar="";
  if($struckture->parts)
        {
   foreach($struckture->parts as $key => $value)
   {
    $enc=$struckture->parts[$key]->encoding;
    if($struckture->parts[$key]->ifdparameters)
    {
     $name=$struckture->parts[$key]->dparameters[0]->value;
     $message = imap_fetchbody($this->marubox,$mid,$key+1);
     switch ($enc)
     {
      case 0:
       $message = imap_8bit($message);
       break;
      case 1:
       $message = imap_8bit ($message);
       break;
      case 2:
       $message = imap_binary ($message);
       break;
      case 3:
       $message = imap_base64 ($message);
       break;
      case 4:
       $message = quoted_printable_decode($message);
       break;
      case 5:
       $message = $message;
       break;
     }
     $fp=fopen($path.$name,"w");
     fwrite($fp,$message);
     fclose($fp);
     $ar=$ar.$name.",";
    }
    // Support for embedded attachments starts here
    if($struckture->parts[$key]->parts)
    {
     foreach($struckture->parts[$key]->parts as $keyb => $valueb)
     {
      $enc=$struckture->parts[$key]->parts[$keyb]->encoding;
      if($struckture->parts[$key]->parts[$keyb]->ifdparameters)
      {
       $name=$struckture->parts[$key]->parts[$keyb]->dparameters[0]->value;
       $partnro = ($key+1).".".($keyb+1);
       $message = imap_fetchbody($this->marubox,$mid,$partnro);
       switch ($enc)
       {
        case 0:
           $message = imap_8bit($message);
         break;
        case 1:
           $message = imap_8bit ($message);
         break;
        case 2:
           $message = imap_binary ($message);
         break;
        case 3:
           $message = imap_base64 ($message);
         break;
        case 4:
           $message = quoted_printable_decode($message);
         break;
        case 5:
           $message = $message;
         break;
       }
       $fp=fopen($path.$name,"w");
       fwrite($fp,$message);
       fclose($fp);
       $ar=$ar.$name.",";
      }
     }
    }    
   }
  }
  $ar=substr($ar,0,(strlen($ar)-1));
  return $ar;
 }
 
 function getBody($mid) // Get Message Body
 {
  if(!$this->marubox)
  {
   return false;
  }
  $body = $this->get_part($this->marubox, $mid, "TEXT/HTML");
  if ($body == "")
  {
   $body = $this->get_part($this->marubox, $mid, "TEXT/PLAIN");
  }
  if ($body == "")
  {
   return "";
  }
  return $this->_iconv_utf8($body);
 }
 
 function deleteMails($mid) // Delete That Mail
 {
  if(!$this->marubox)
   return false;
 
  imap_delete($this->marubox,$mid);
 }
 
 function close_mailbox() //Close Mail Box
 {
  if(!$this->marubox)
   return false;

  imap_close($this->marubox,CL_EXPUNGE);
 }
 
 function _imap_utf8($text)
 {
  if(preg_match('/=?([a-zA-z0-9-]+)?(.*)?=/i', $text, $match))
  {
   $text = imap_utf8($text);
   if(strtolower(substr($match[1], 0, 2)) == 'gb')
   {
    $text = iconv('gbk', 'utf-8', $text);
   }
   return $text;
  }
  return $this->_iconv_utf8($text);
 }
 
 function _iconv_utf8($text)
 {
  $s1 = iconv('gbk', 'utf-8', $text);
  $s0 = iconv('utf-8', 'gbk', $s1);
  if($s0 == $text)
  {
   return $s1;
  }
  else
  {
   return $text;
  }
 }
}

面是一个php邮件发送的类的一个函数。

 代码如下 复制代码

function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "")
    {
        $mail_from = $this->get_address($this->strip_comment($from));
        $body = ereg_replace("(^|(rn))(.)", "1.3", $body);
        $header = "MIME-Version:1.0rn";

        if($mailtype=="HTML"){
            $header .= "Content-Type:text/htmlrn";
        }

        $header .= "To: ".$to."rn";

        if ($cc != "") {
            $header .= "Cc: ".$cc."rn";
        }

        $header .= "From: 报名邮件.<".$from.">rn";
        $header .= "Subject: ".$subject."rn";
        $header .= $additional_headers;
        $header .= "Date: ".date("r")."rn";
        $header .= "X-Mailer:By Redhat (PHP/".phpversion().")rn";
  $utfheader=iconv("UTF-8","GB2312",$header);
        list($msec, $sec) = explode(" ", microtime());

        $header .= "Message-ID: <".date("YmdHis", $sec).".".($msec*1000000).".".$mail_from.">rn";

        $TO = explode(",", $this->strip_comment($to));

        if ($cc != "") {
            $TO = array_merge($TO, explode(",", $this->strip_comment($cc)));
        }

        if ($bcc != "") {
            $TO = array_merge($TO, explode(",", $this->strip_comment($bcc)));
        }

        $sent = TRUE;

        foreach ($TO as $rcpt_to) {
            $rcpt_to = $this->get_address($rcpt_to);

            if (!$this->smtp_sockopen($rcpt_to)) {
                $this->log_write("Error: Cannot send email to ".$rcpt_to."n");
                $sent = FALSE;
                continue;
            }

            if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $utfheader, $body)) {
                $this->log_write("E-mail has been sent to <".$rcpt_to.">n");
            } else {
                $this->log_write("Error: Cannot send email to <".$rcpt_to.">n");
                $sent = FALSE;
            }

            fclose($this->sock);

            $this->log_write("Disconnected from remote hostn");
        }
        return $sent;
    }

我们如何调用这个类呢?
再看示例

 代码如下 复制代码

  include("sendmail.php");//发送邮件类
  ####################--发邮件--####################
  $smtpserver  =  "smtp.126.com";//SMTP服务器
  $smtpserverport = 25;//SMTP服务器端口
  $smtpusermail  =  "test@126.com";//SMTP服务器的用户邮箱
  $smtpuser   =  "test";//SMTP服务器的用户帐号
  $smtppass   =  "123456";//SMTP服务器的用户密码

  $smtpemailto  =  "dianzhong@126.com";//发送给谁
  $mailsubject  =  $username.'报名!';//邮件主题
  $mailtime  = date("Y-m-d H:i:s");
  $mailbody   =  $content;//邮件内容

  $utfmailbody = iconv("UTF-8","GB2312",$mailbody);//转换邮件编码
  $mailtype   =  "HTML";//邮件格式(HTML/TXT),TXT为文本邮件


在这里需要一个smtp服务器。我们可以注册一个126的邮箱。 在上面的代码中,修改成你自己注册的邮箱地址和用户名、密码即可。

[!--infotagslink--]

相关文章

  • NodeJS实现阿里大鱼短信通知发送

    本文给大家介绍的是nodejs实现使用阿里大鱼短信API发送消息的方法和代码,有需要的小伙伴可以参考下。...2016-01-20
  • PHP测试成功的邮件发送案例

    mail()函数的作用:连接到邮件服务器,利用smtp协议,与该服务器交互并投邮件。注意:1、mail函数不支持esmtp协议,---即,只能直投,不能登陆2、由上条,我们只能直投至最终的收件服务器地址.而该地址,又是在PHP.ini中指定的,所...2015-10-30
  • php邮件发送的两种方式

    这篇文章研究的主要内容就是使用PHP来发送电子邮件,总结为以下两种方法:一、使用PHP内置的mail()函数<&#63;php $to = "test@163.com"; //收件人 $subject = "Test"; //主题 $message = "This is a test mail!"; //正文...2015-10-30
  • c# 实现发送邮件的功能

    这篇文章主要介绍了c# 如何实现发送邮件的功能,文中示例代码非常详细,帮助大家更好的理解和学习,感兴趣的朋友可以了解下...2020-07-07
  • php邮件发送的两种方式

    这篇文章研究的主要内容就是使用PHP来发送电子邮件,总结为以下两种方法:一、使用PHP内置的mail()函数<&#63;php $to = "test@163.com"; //收件人 $subject = "Test"; //主题 $message = "This is a test mail!"; //正文...2015-10-30
  • python实现企业微信定时发送文本消息的实例代码

    这篇文章主要介绍了python实现企业微信定时发送文本消息的实例代码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-11-25
  • c#使用netmail方式发送邮件示例

    这篇文章主要介绍了c#使用netmail方式发送邮件的示例,大家参考使用吧...2020-06-25
  • PHP测试成功的邮件发送案例

    mail()函数的作用:连接到邮件服务器,利用smtp协议,与该服务器交互并投邮件。注意:1、mail函数不支持esmtp协议,---即,只能直投,不能登陆2、由上条,我们只能直投至最终的收件服务器地址.而该地址,又是在PHP.ini中指定的,所...2015-10-30
  • PHPMailer在SAE上无法发送邮件的解决方法

    PHPMailer在SAE上无法发送邮件怎么回事呢,我们以前在php5.2.7版本中使用了PHPMailer是可以发,但移到sae中发现无法发邮件了,那么此问题如何解决 在SAE上直接用5.2.7...2016-11-25
  • 整理几个android后台发送邮件的方法

    本文我们整理了三个android后台发送邮件的方法及示例,第一个是不借助Intent在android后台发送Email,第二个是用在收集应用的异常信息,第三个是分享一个android后台发送邮...2016-09-20
  • Perl中使用MIME::Lite发送邮件实例

    这篇文章主要介绍了Perl中使用MIME::Lite发送邮件实例,本文介绍了使用sendmail方式发送、发送HTML格式邮件、smtp方式发送邮件等内容,需要的朋友可以参考下...2020-06-29
  • 网上找到的两个PHP发送邮件的例子,很不错,贴出来给初学者参考吧(不知道是否有兄弟曾贴过),呵呵(2

    Advanced Example Here we will show the full capabilities of the PHP mail function. PHP Code: <?php echo "<html><body>"; $recipient = "Kris Arndt <karn@nu...2016-11-25
  • PHP利用Jmail组件实现发送邮件

    学过asp的朋友可能知道jmail组件是使用在asp中一个常用的邮箱发送功能,在php中如果想调用jmail功能我们需要使用com组件来操作。 我们先来介绍格式 代码如...2016-11-25
  • phpMailer 发送邮件

    //原创:www.111cn.net 注明:转载说明来处www.111cn.net // 昨天听一网友说用php 里面的mail发邮件发不出去,我想一般都是发不了的,现在大多数据邮件提供商都不准那样了...2016-11-25
  • C#编程实现发送邮件的方法(可添加附件)

    这篇文章主要介绍了C#编程实现发送邮件的方法,具备添加附件的功能,涉及C#文件传输及邮件发送的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • php中利用curl smtp发送邮件实例

    本文章来介绍人一下关于与我们不同的发送邮件的方法我们来利用php curl stmp来实现邮件的发送程序。 $ telnet 邮箱SMTP服务地址 25 Trying 邮箱服务IP地址......2016-11-25
  • Python基于httpx模块实现发送请求

    这篇文章主要介绍了Python基于httpx模块实现发送请求,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-07-08
  • node.js 基于 STMP 协议和 EWS 协议发送邮件

    这篇文章主要介绍了node.js 基于 STMP 协议和 EWS 协议发送邮件的示例,帮助大家更好的理解和使用node.js,感兴趣的朋友可以了解下...2021-02-15
  • php定时发送邮件

    <?php // 请求 PHPmailer类 文件 require_once("class.phpmailer.php"); //发送Email函数 function smtp_mail ( $sendto_email, $subject, $body, $extra_hd...2016-11-25
  • 解决PHPMailer错误SMTP Error: Could not connect to SMTP host的办法

    PHPMailer发邮件时提示SMTP Error: Could not connect to SMTP host错误是smtp服务器的问题我们一起来看看关于SMTP Error: Could not connect to SMTP host问题的解...2016-11-25