PHP发邮件函数实现代码

 更新时间:2016年11月25日 17:01  点击:2038

不需要邮件服务器,不使用mail内置函数,一个类就搞定,利用php教程mailer类我写了一个自定义函数 sendmail() ,very实用!

以前也在几个php论坛上发表过这个发邮件的函数,今天再发,因为today要附上使用例子,如果你还不会用,那就要补补php基础课了。

  1.准备文件 sendmail.class.php文件、phpmailer类     下载  

2.下载后,解压 phpmailer.rar 到服务器的任何目录下

3.打开 sendmail.class.php ,修改如下(浅黄色部分是必须 要修改的变量值)

 // 以下 5 个变量值必须据实修改
 $host     = '61.183.41.172';
 $username = 'admin@php95.com';
 $password = "******"     
 $from     = 'admin@php95.com';   
 $fromname = '天马博客';  

// 先设置 $to $subject $content 这三个变量的值,再调用 sendmail 函数来发送邮件
$to = 'nt2030@qq.com';
$subject = '测试phpmailer类发送邮件';
$content = '测试phpmailer类发送邮件';
sendmail($to,$subject,$content);

4.修改 sendmail.class.php 完毕后,运行它..

你的邮件是否发送成功?

天马测试本代码,is ok,见证:

 点击查看原图

语法
mail(to,subject,message,headers,parameters)参数 描述
to 必需。规定 email 接收者。
subject 必需。规定 email 的主题。注释:该参数不能包含任何新行字符。
message 必需。定义要发送的消息。应使用 lf (n) 来分隔各行。
headers 可选。规定附加的标题,比如 from、cc 以及 bcc。

应当使用 crlf (rn) 分隔附加的标题。
 
parameters 可选。对邮件发送程序规定额外的参数。


*/
$to='nobody@example.com';        //定义邮箱地址
$subject='mail';           //定义发送邮件的主题
$message='hello,php';         //定义邮件主体内容
$headers='from:webmaster@example.com'."rn".
'reply-to:webmaster@example.com'."rn".
 'x-mailer:php/'.phpversion();        //定义附加信息
mail($to,$subject,$message,$headers);      //发送邮件
?>
<?php
//发送html格式的邮件例子
$to='test@example.com'.',';
$to.='test1@example.com';        //定义多个收件人地址
$subject='mailhtml';          //定义邮件标题
//下面是邮件的html代码
$message='
<html>
<head>
<title>birthday reminders for august</title>
</head>
<body>
<p>here are the birthdays upcoming in august!</p>
<table>
  <tr>
    <th>person</th><th>day</th><th>month</th><th>year</th>
  </tr>
  <tr>
    <td>joe</td><td>3rd</td><td>august</td><td>1970</td>
  </tr>
  <tr>
    <td>sally</td><td>17th</td><td>august</td><td>1973</td>
  </tr>
</table>
</body>
</html>
';
//发送http请求
$headers='mime-version:1.0'."rn";        //定义附加信息
$headers.='content-type:text/html;charset=iso-8856-1'."rn";
$headers.='to:mary<mary@example.com>,kelly<kelly@example.com>'."rn";
$headers.='from:birthday reminder<birthday@example.com>'."rn";
$headers.='cc:birthdayarchive@example.com'."rn";
$headers.='bcc:birthdaycheck@example.com'."rn";
mail($to,$subject,$message,$headers);       //执行发送操作

/*

注释:php 需要一个已安装且正在运行的邮件系统,以便使邮件函数可用。所用的程序通过在 php.ini 文件中的配置设置进行定义

*/

以前都是利用mail函数或phpermail进行邮件发送,今天看这款利用qmail进行邮件发送,写法非常简单,是一款不错的工具。

function send_check_mail($email, $subject,$uid,$buffer)
{
    echo "hello";
 $command = "/var/qmail/bin/qmail-inject ".$email; //qmail程序地址,$email是要发送的地址
 $handle = popen($command, "w"); //打开管道
 if (!$handle) {
  return false;
 }

 $from = "yangxuemei2012@111cn.net"; //发件人
 fwrite($handle, "from: ".$from."n"); //往管道写数据
 fwrite($handle, "return-path: ".$from."n");
 fwrite($handle, "to: ".$uid."n");
 fwrite($handle, "subject: ".$subject."n");
 fwrite($handle, "mime-version: 1.0n");
 fwrite($handle, "content-type: text/html; charset="gb2312"nn");
 fwrite($handle, $buffer."n");
 pclose($handle); //关闭管道

 return true;
}
$subject = "测试邮件";

$uid = $_post['uid']; //from信息
$content= "<html><body>".$u_email

   ." 您好!<br><br>谢谢,www.111cn.net!<br</body></html>"; //内容信息

$u_email = "machunjie2003@111cn.net"; //发送到的邮箱
if (send_check_mail($u_email, $subject, $uid, $content)) {

 echo "恭喜!发送投票邮件到您的邮箱!<br><br>请检查您的邮箱:<font color=#cc0033>".$u_email." </font><br><br>". $close;
 } else {

 echo "很不幸,发送投票邮件到您的邮箱失败,请重试或者联系开发人员。<br><br>". $close;

}

 代码如下 复制代码

$pdfname="test.pdf";
$email="test@test.com";
$text = "您好,附件中是您需要的pdf文件。请点击下载。<br><a href=http://www.111cn.net>www.111cn.net</a>";         //文本内容

$text = base64_encode($text);     //用base64方法把它编码
$text = chunk_split($text);     //把这个长字符串切成由每行76个字符组成的小块

$subject = $pdfname;         //标题
$from = "admin@111cn.net";     //发送者
$to = $email;     //接受者

//附件
// 定义分界线
$boundary = "nextpart_".uniqid("");
$boundary2 = "nextpart_".uniqid("");
$headers = "to: $torn";
$headers .= "from: $fromrn";
$headers .="mime-version: 1.0rn";
$headers .= "content-type: multipart/mixed;
            boundary="----=_$boundary"rn";

$read=file_get_contents($pdfname);

$read = base64_encode($read);     //用base64方法把它编码
$read = chunk_split($read);     //把这个长字符串切成由每行76个字符组成的小块

//现在我们可以建立邮件的主体
$body = "this is a multi-part message in mime format.

------=_$boundary
content-type: multipart/alternative;
    boundary="----=_$boundary2";

------=_$boundary2
content-type: text/html;
    charset="gbk"
content-transfer-encoding: base64

$text

------=_$boundary2--

------=_$boundary
content-type: application/octet-stream;
    charset="gbk";
    name="$pdfname"
content-disposition: attachment; filename="$pdfname"
content-transfer-encoding: base64

$read

-------=_$boundary--";

if(mail($to, $subject,$body,$headers))
   echo "您需要的pdf文件(".$pdfname.")已经发往您的邮箱:".$to."。<br>请查收。";
else
   echo "抱歉,发送失败了。<br>";


   ?>

用的mail()函数,感觉不好用,而且感觉这个邮件地址不能太多,一次copy了100个可能会出问题,下面提供一款可以限制发送邮件php类函数。
*/

 代码如下 复制代码

class sendmail{
    function __construct(){
        $this->set();
        $this->auth = 1;
    }

    function set($server=yj_sysmail_smtp,$user="",$password=yj_sysmail_pass,$port=yj_sysmailport,$type=1,$mailusername=0){
        $user=($user=="")?substr(yj_sysmail,0,stripos(yj_sysmail,"@")):$user;

        $this->type = $type;
        $this->server = $server;
        $this->port = $port;
        $this->user = $user;
        $this->password = $password;
        $this->mailusername = $mailusername;
    }

    function send($email_to, $email_subject, $email_message, $email_from = ''){
        $email_subject = '=?utf-8?b?'.base64_encode(str_replace("r", '', $email_subject)).'?=';
        $email_message = str_replace("rn.", " rn..", str_replace("n", "rn", str_replace("r", "n", str_replace("rn", "n", str_replace("nr", "r", $email_message)))));
        $email_from = $email_from == '' ? '=?utf-8?b?'.base64_encode(yj_sysname)."?= <".yj_sysmail.">" : (preg_match('/^(.+?) <(.+?)>$/',$email_from, $from) ? '=?utf-8?b?'.base64_encode($from[1])."?= <$from[2]>" : $email_from);
        $emails = explode(',', $email_to);
        foreach($emails as $touser){
            $tousers[] = preg_match('/^(.+?) <(.+?)>$/',$touser, $to) ? ($this->mailusername ? '=?utf-8?b?'.base64_encode($to[1])."?= <$to[2]>" : $to[2]) : $touser;
        }
        $email_to = implode(',', $tousers);
        $headers = "mime-version: 1.0rnto: {$email_to}rnfrom: {$email_from}<{$email_from}>rnx-priority: 3rnx-mailer: eglive rndate: ".date("r")."rncontent-type: text/html; charset=utf-8rn";

        if($this->type == 1){
            return $this->smtp($email_to, $email_subject, $email_message, $email_from, $headers);
        }elseif($this->type == 2){
            return @mail($email_to, $email_subject, $email_message, $headers);
        }else{
            ini_set('smtp', $this->server);
            ini_set('smtp_port', $this->port);
            ini_set('sendmail_from', $email_from);
            return @mail($email_to, $email_subject, $email_message, $headers);
        }
    }

    function smtp($email_to, $email_subject, $email_message, $email_from = '', $headers = ''){
        if(!$fp = @fsockopen($this->server, $this->port, $errno, $errstr, 10)){
            $this->errorlog('smtp', "($this->server:$this->port) connect - unable to connect to the smtp server", 0);
            return false;
        }
        stream_set_blocking($fp, true);
        $lastmessage = fgets($fp, 512);
        if(substr($lastmessage, 0, 3) != '220'){
            $this->errorlog('smtp', "$this->server:$this->port connect - $lastmessage", 0);
            return false;
        }
        fputs($fp, ($this->auth ? 'ehlo' : 'helo')." phpcmsrn");
        $lastmessage = fgets($fp, 512);
        if(substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250){
            $this->errorlog('smtp', "($this->server:$this->port) helo/ehlo - $lastmessage", 0);
            return false;
        }
        while(1){
            if(substr($lastmessage, 3, 1) != '-' || empty($lastmessage)){
                break;
            }
            $lastmessage = fgets($fp, 512);
        }
        fputs($fp, "auth loginrn");
        $lastmessage = fgets($fp, 512);
        if(substr($lastmessage, 0, 3) != 334){
            $this->errorlog('smtp', "($this->server:$this->port) auth login - $lastmessage", 0);
            return false;
        }
        fputs($fp, base64_encode($this->user)."rn");
        $lastmessage = fgets($fp, 512);
        if(substr($lastmessage, 0, 3) != 334){
            $this->errorlog('smtp', "($this->server:$this->port) username - $lastmessage", 0);
            return false;
        }
        fputs($fp, base64_encode($this->password)."rn");
        $lastmessage = fgets($fp, 512);
        if(substr($lastmessage, 0, 3) != 235){
            $this->errorlog('smtp', "($this->server:$this->port) password - $lastmessage", 0);
            return false;
        }
        fputs($fp, "mail from: <".preg_replace("/.*<(.+?)>.*/", "", $email_from).">rn");
        $lastmessage = fgets($fp, 512);
        if(substr($lastmessage, 0, 3) != 250){
            fputs($fp, "mail from: <".preg_replace("/.*<(.+?)>.*/", "", $email_from).">rn");
            $lastmessage = fgets($fp, 512);
            if(substr($lastmessage, 0, 3) != 250){
                $this->errorlog('smtp', "($this->server:$this->port) mail from - $lastmessage", 0);
                return false;
            }
        }
        $email_tos = array();
        $emails = explode(',', $email_to);
        foreach($emails as $touser){
            $touser = trim($touser);
            if($touser){
                fputs($fp, "rcpt to: <".preg_replace("/.*<(.+?)>.*/", "", $touser).">rn");
                $lastmessage = fgets($fp, 512);
                if(substr($lastmessage, 0, 3) != 250){
                    fputs($fp, "rcpt to: <".preg_replace("/.*<(.+?)>.*/", "", $touser).">rn");
                    $lastmessage = fgets($fp, 512);
                    $this->errorlog('smtp', "($this->server:$this->port) rcpt to - $lastmessage", 0);
                    return false;
                }
            }
        }
        fputs($fp, "datarn");
        $lastmessage = fgets($fp, 512);
        if(substr($lastmessage, 0, 3) != 354){
            $this->errorlog('smtp', "($this->server:$this->port) data - $lastmessage", 0);
        }
        $headers .= 'message-id: <'.gmdate('ymdhs').'.'.substr(md5($email_message.microtime()), 0, 6).rand(100000, 999999).'@'.$_server['http_host'].">rn";
        fputs($fp, "date: ".gmdate('r')."rn");
        fputs($fp, "to: ".$email_to."rn");
        fputs($fp, "subject: ".$email_subject."rn");
        fputs($fp, $headers."rn");
        fputs($fp, "rnrn");
        fputs($fp, "$email_messagern.rn");
        $lastmessage = fgets($fp, 512);
        fputs($fp, "quitrn");
        return true;
    }

    function errorlog($type, $message, $is){
        $this->error[] = array($type, $message, $is);
    }

    function mailmess($mess=""){
        return "<style>*{font-family:verdana;font-size:13px;/*www.111cn.net提供*/}</style>
        <table cellpadding='5' cellspacing='1' border='0' width='750' style='background-color:#fff;border:1px solid #3b5998;padding:15px;'>
        <tr><td style='background:#3b5998;color:#fff;font-weight:bold;font-size:14px;'>".yj_syscnname." - ".yj_sysname."</td></tr>
        <tr><td>{$mess}</td></tr>
      
        </table>";
    }
}

[!--infotagslink--]

相关文章

  • php正确禁用eval函数与误区介绍

    eval函数在php中是一个函数并不是系统组件函数,我们在php.ini中的disable_functions是无法禁止它的,因这他不是一个php_function哦。 eval()针对php安全来说具有很...2016-11-25
  • php中eval()函数操作数组的方法

    在php中eval是一个函数并且不能直接禁用了,但eval函数又相当的危险了经常会出现一些问题了,今天我们就一起来看看eval函数对数组的操作 例子, <?php $data="array...2016-11-25
  • Python astype(np.float)函数使用方法解析

    这篇文章主要介绍了Python astype(np.float)函数使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-08
  • Python中的imread()函数用法说明

    这篇文章主要介绍了Python中的imread()函数用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-16
  • C# 中如何取绝对值函数

    本文主要介绍了C# 中取绝对值的函数。具有很好的参考价值。下面跟着小编一起来看下吧...2020-06-25
  • C#学习笔记- 随机函数Random()的用法详解

    下面小编就为大家带来一篇C#学习笔记- 随机函数Random()的用法详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • 不打开网页直接查看网站的源代码

      有一种方法,可以不打开网站而直接查看到这个网站的源代码..   这样可以有效地防止误入恶意网站...   在浏览器地址栏输入:   view-source:http://...2016-09-20
  • php 调用goolge地图代码

    <?php require('path.inc.php'); header('content-Type: text/html; charset=utf-8'); $borough_id = intval($_GET['id']); if(!$borough_id){ echo ' ...2016-11-25
  • JS基于Mootools实现的个性菜单效果代码

    本文实例讲述了JS基于Mootools实现的个性菜单效果代码。分享给大家供大家参考,具体如下:这里演示基于Mootools做的带动画的垂直型菜单,是一个初学者写的,用来学习Mootools的使用有帮助,下载时请注意要将外部引用的mootools...2015-10-23
  • JS+CSS实现分类动态选择及移动功能效果代码

    本文实例讲述了JS+CSS实现分类动态选择及移动功能效果代码。分享给大家供大家参考,具体如下:这是一个类似选项卡功能的选择插件,与普通的TAb区别是加入了动画效果,多用于商品类网站,用作商品分类功能,不过其它网站也可以用,...2015-10-21
  • JS实现自定义简单网页软键盘效果代码

    本文实例讲述了JS实现自定义简单网页软键盘效果。分享给大家供大家参考,具体如下:这是一款自定义的简单点的网页软键盘,没有使用任何控件,仅是为了练习JavaScript编写水平,安全性方面没有过多考虑,有顾虑的可以不用,目的是学...2015-11-08
  • php 取除连续空格与换行代码

    php 取除连续空格与换行代码,这些我们都用到str_replace与正则函数 第一种: $content=str_replace("n","",$content); echo $content; 第二种: $content=preg_replac...2016-11-25
  • 金额阿拉伯数字转换为中文的自定义函数

    CREATE FUNCTION ChangeBigSmall (@ChangeMoney money) RETURNS VarChar(100) AS BEGIN Declare @String1 char(20) Declare @String2 char...2016-11-25
  • php简单用户登陆程序代码

    php简单用户登陆程序代码 这些教程很对初学者来讲是很有用的哦,这款就下面这一点点代码了哦。 <center> <p>&nbsp;</p> <p>&nbsp;</p> <form name="form1...2016-11-25
  • C++中 Sort函数详细解析

    这篇文章主要介绍了C++中Sort函数详细解析,sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变...2022-08-18
  • Android开发中findViewById()函数用法与简化

    findViewById方法在android开发中是获取页面控件的值了,有没有发现我们一个页面控件多了会反复研究写findViewById呢,下面我们一起来看它的简化方法。 Android中Fin...2016-09-20
  • PHP实现清除wordpress里恶意代码

    公司一些wordpress网站由于下载的插件存在恶意代码,导致整个服务器所有网站PHP文件都存在恶意代码,就写了个简单的脚本清除。恶意代码示例...2015-10-23
  • PHP用strstr()函数阻止垃圾评论(通过判断a标记)

    strstr() 函数搜索一个字符串在另一个字符串中的第一次出现。该函数返回字符串的其余部分(从匹配点)。如果未找到所搜索的字符串,则返回 false。语法:strstr(string,search)参数string,必需。规定被搜索的字符串。 参数sea...2013-10-04
  • JS实现双击屏幕滚动效果代码

    本文实例讲述了JS实现双击屏幕滚动效果代码。分享给大家供大家参考,具体如下:这里演示双击滚屏效果代码的实现方法,不知道有觉得有用处的没,现在网上还有很多还在用这个特效的呢,代码分享给大家吧。运行效果截图如下:在线演...2015-10-30
  • js识别uc浏览器的代码

    其实挺简单的就是if(navigator.userAgent.indexOf('UCBrowser') > -1) {alert("uc浏览器");}else{//不是uc浏览器执行的操作}如果想测试某个浏览器的特征可以通过如下方法获取JS获取浏览器信息 浏览器代码名称:navigator...2015-11-08