发送邮件代码-php 发送邮件代码

 更新时间:2016年11月25日 17:02  点击:1960
本文章是利用phpmailer来实现在线发送邮件功能的源码代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>--邀请好友参加</title>
<style type="text/css">
<!--
body {
 margin: 0px;
 padding: 0px;
 font-size: 12px;
 background-color: #CFCFCF;
}
input {
 line-height: 18px;
 height: 18px;
 border: 1px solid #CCCCCC;
}
img {
 border-top-width: 0px;
 border-right-width: 0px;
 border-bottom-width: 0px;
 border-left-width: 0px;
}
* {
 margin: 0px;
 padding: 0px;
 list-style-image: none;
 list-style-type: none;
 background-repeat: no-repeat;
}
td {
 line-height: 22px;
 font-size: 14px;
 font-weight: 700;
 color: #276662;
}
-->
</style>
</head>

<body>

<form action="#" method="post" name="form">
<table border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td width="572" height="227" valign="top" background="img/mailfooterimg.gif"><table width="95%" border="0" align="center" cellpadding="0" cellspacing="0">
      <tr>
        <td height="70">&nbsp;</td>
      </tr>
      <tr>
        <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
          <tr>
            <td><input type="text" value="http://111cn.net/" size="60" /></td>
            <td height="40"><a href="#"><img src="img/copy.gif" width="72" height="22" /></a></td>
          </tr>
        </table></td>
      </tr>
      <tr>
        <td height="28">好友姓名:
          <input type="text" size="22" />
          &nbsp;&nbsp;
          邮箱地址:
          <input type="text" size="22" />        </td>
      </tr>
      <tr>
        <td height="28">好友姓名:
          <input type="text" size="22" />
          &nbsp;&nbsp;
          邮箱地址:
          <input type="text" size="22" />        </td>
      </tr>
      <tr>
        <td height="28">好友姓名:
          <input type="text" size="22" />
          &nbsp;&nbsp;
          邮箱地址:
          <input type="text" size="22" />        </td>
      </tr>
      <tr>
        <td height="28" align="right"><a href="#"><img src="img/sendbtn.gif" width="95" height="26" /></a></td>
      </tr>
    </table></td>
  </tr>
</table>
</form>
</body>
</html>
发送邮件处理功能页面。

mail.php

<?

require(dirname(__FILE__)."/mail/class.phpmailer.php"); //调用 phpmailer类型,如果没有phpmailer请点击这里下载phpmailer for php5/6 下载

$array =  array_unique(Get_value('mail',1));//去除重复的邮箱地址

$mail = new PHPMailer(); 
 $count =0; 
 $bad =0;
 $mail->IsSMTP();                                      // set mailer to use SMTP
 $mail->Host = "smtp.163.com";  // smtp1.example.com;smtp2.example.comspecify main and backup server
 $mail->SMTPAuth = true;     // turn on SMTP authentication
 $mail->Username = "mailangel123";  // SMTP username
 $mail->Password = "*******"; // SMTP password
 
 $mail->From = "mailangel123@163.com";
 $mail->FromName = "你的好友来信";
 $MailBody = '内容'

$mail->AddReplyTo("mailangel123@163.com", "澳优");
   $mail->AddAddress($tmpmail,'您好!');
   $mail->WordWrap = 50;
   $mail->CharSet="GB2312";                                
   //$mail->AddAttachment("/var/tmp/file.tar.gz");       
   //$mail->AddAttachment("/tmp/image.jpg", "new.jpg");  
   $mail->IsHTML(true);                           
   
   $mail->Subject = "你的朋友邀请你一起合影!";
   $mail->Body    = $MailBody;
   
   if(!$mail->Send())
   {
      $bad++;
      $mail->ClearAddresses();  
      $mail->ClearAttachments();
     
   }

OK就完成了哦。

?>

<?php
class smtp
{
/* Public Variables */
var $smtp_port;
var $time_out;
var $host_name;
var $log_file;
var $relay_host;
var $debug;
var $auth;
var $user;
var $pass;
/* Private Variables */
var $sock;
/* Constractor */
function smtp($relay_host = "", $smtp_port = 25,$auth = false,$user,$pass)
{
$this->debug = FALSE;
$this->smtp_port = $smtp_port;
$this->relay_host = $relay_host;
$this->time_out = 30; //is used in fsockopen()
#
$this->auth = $auth;//auth
$this->user = $user;
$this->pass = $pass;
#
$this->host_name = "localhost"; //is used in HELO command
$this->log_file ="";
$this->sock = FALSE;
}
/* Main Function */
function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "")
{
$mail_from = $this->get_address($this->strip_comment($from));
$body = ereg_replace("(^|(rn))(\.)", "[url=file://\1.\3]\1.\3[/url]", $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<".$from.">rn";
$header .= "Subject: ".$subject."rn";
$header .= $additional_headers;
$header .= "Date: ".date("r")."rn";
$header .= "X-Mailer:By Redhat (PHP/".phpversion().")rn";
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, $header, $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");
}
echo "<br>";
echo $header;
return $sent;
}
/* Private Functions */
function smtp_send($helo, $from, $to, $header, $body = "")
{
if (!$this->smtp_putcmd("HELO", $helo)) {
return $this->smtp_error("sending HELO command");
}
#auth
if($this->auth){
if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {
return $this->smtp_error("sending HELO command");
}
if (!$this->smtp_putcmd("", base64_encode($this->pass))) {
return $this->smtp_error("sending HELO command");
}
}
#
if (!$this->smtp_putcmd("MAIL", "FROM:<".$from.">")) {
return $this->smtp_error("sending MAIL FROM command");
}
if (!$this->smtp_putcmd("RCPT", "TO:<".$to.">")) {
return $this->smtp_error("sending RCPT TO command");
}
if (!$this->smtp_putcmd("DATA")) {
return $this->smtp_error("sending DATA command");
}
if (!$this->smtp_message($header, $body)) {
return $this->smtp_error("sending message");
}
if (!$this->smtp_eom()) {
return $this->smtp_error("sending <CR><LF>.<CR><LF> [EOM]");
}
if (!$this->smtp_putcmd("QUIT")) {
return $this->smtp_error("sending QUIT command");
}
return TRUE;
}
function smtp_sockopen($address)
{
if ($this->relay_host == "") {
return $this->smtp_sockopen_mx($address);
} else {
return $this->smtp_sockopen_relay();
}
}
function smtp_sockopen_relay()
{
$this->log_write("Trying to ".$this->relay_host.":".$this->smtp_port."n");
$this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out);
if (!($this->sock && $this->smtp_ok())) {
$this->log_write("Error: Cannot connenct to relay host ".$this->relay_host."n");
$this->log_write("Error: ".$errstr." (".$errno.")n");
return FALSE;
}
$this->log_write("Connected to relay host ".$this->relay_host."n");
return TRUE;;
}
function smtp_sockopen_mx($address)
{
$domain = ereg_replace("[url=mailto:^.+@([^@]+)$]^.+@([^@]+)$[/url]", "[url=file://\1]\1[/url]", $address);
if (!@getmxrr($domain, $MXHOSTS)) {
$this->log_write("Error: Cannot resolve MX "".$domain.""n");
return FALSE;
}
foreach ($MXHOSTS as $host) {
$this->log_write("Trying to ".$host.":".$this->smtp_port."n");
$this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);
if (!($this->sock && $this->smtp_ok())) {
$this->log_write("Warning: Cannot connect to mx host ".$host."n");
$this->log_write("Error: ".$errstr." (".$errno.")n");
continue;
}
$this->log_write("Connected to mx host ".$host."n");
return TRUE;
}
$this->log_write("Error: Cannot connect to any mx hosts (".implode(", ", $MXHOSTS).")n");
return FALSE;
}
function smtp_message($header, $body)
{
fputs($this->sock, $header."rn".$body);
$this->smtp_debug("> ".str_replace("rn", "n"."> ", $header."n> ".$body."n> "));
return TRUE;
}
function smtp_eom()
{
fputs($this->sock, "rn.rn");
$this->smtp_debug(". [EOM]n");
return $this->smtp_ok();
}
function smtp_ok()
{
$response = str_replace("rn", "", fgets($this->sock, 512));
$this->smtp_debug($response."n");
if (!ereg("^[23]", $response)) {
fputs($this->sock, "QUITrn");
fgets($this->sock, 512);
$this->log_write("Error: Remote host returned "".$response.""n");
return FALSE;
}
return TRUE;
}
function smtp_putcmd($cmd, $arg = "")
{
if ($arg != "") {
if($cmd=="") $cmd = $arg;
else $cmd = $cmd." ".$arg;
}
fputs($this->sock, $cmd."rn");
$this->smtp_debug("> ".$cmd."n");
return $this->smtp_ok();
}
function smtp_error($string)
{
$this->log_write("Error: Error occurred while ".$string.".n");
return FALSE;
}
function log_write($message)
{
$this->smtp_debug($message);
if ($this->log_file == "") {
return TRUE;
}
$message = date("M d H:i:s ").get_current_user()."[".getmypid()."]: ".$message;
if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, "a"))) {
$this->smtp_debug("Warning: Cannot open log file "".$this->log_file.""n");
return FALSE;
}
flock($fp, LOCK_EX);
fputs($fp, $message);
fclose($fp);
return TRUE;
}
function strip_comment($address)
{
$comment = "[url=file://\([^()]*\]\([^()]*\[/url])";
while (ereg($comment, $address)) {
$address = ereg_replace($comment, "", $address);
}
return $address;
}
function get_address($address)
{
$address = ereg_replace("([ trn])+", "", $address);
$address = ereg_replace("^.*<(.+)>.*$", "[url=file://\1]\1[/url]", $address);
return $address;
}
function smtp_debug($message)
{
if ($this->debug) {
echo $message."<br>";
}
}
function get_attach_type($image_tag) { //
$filedata = array();
$img_file_con=fopen($image_tag,"r");
unset($image_data);
while ($tem_buffer=AddSlashes(fread($img_file_con,filesize($image_tag))))
$image_data.=$tem_buffer;
fclose($img_file_con);
$filedata['context'] = $image_data;
$filedata['filename']= basename($image_tag);
$extension=substr($image_tag,strrpos($image_tag,"."),strlen($image_tag)-strrpos($image_tag,"."));
switch($extension){
case ".gif":
$filedata['type'] = "image/gif";
break;
case ".gz":
$filedata['type'] = "application/x-gzip";
break;
case ".htm":
$filedata['type'] = "text/html";
break;
case ".html":
$filedata['type'] = "text/html";
break;
case ".jpg":
$filedata['type'] = "image/jpeg";
break;
case ".tar":
$filedata['type'] = "application/x-tar";
break;
case ".txt":
$filedata['type'] = "text/plain";
break;
case ".zip":
$filedata['type'] = "application/zip";
break;
default:
$filedata['type'] = "application/octet-stream";
break;
}

return $filedata;
}
}
?>
send.php:
$title                   = $_POST['title'];
$Message            = $_POST['Message'];
$obj_title           = iconv('UTF-8','Shift-JIS',$title);
$obj_message    = iconv('UTF-8', 'Shift-JIS',$Message);
$smtpserver     = "smtp.163.com";//SMTP服务器
  $smtpserverport =25;//SMTP服务器端口
  $smtpusermail   = "";//SMTP服务器的用户邮箱
  $smtpemailto    = "";//发送给谁
  $smtpuser       = "";  //SMTP服务器的用户帐号
  $smtppass       = "";//SMTP服务器的用户密码
  $mailsubject    = $title;//邮件主题
  $mailbody       = $Message  ;//邮件内容
  $mailtype       = "HTML";//邮件格式(HTML/TXT),TXT为文本邮件
  $smtp           = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
$smtp->debug = true;//是否显示发送的调试信息
$smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);

我们利用 phpmailer功能实现 邮件发送功能哦,这里还利用了模板呢,就是读取指定文件内容再发送给朋友。

<?php
@session_start(); 
 include(dirname(__FILE__).'./inc/function.php');
 require(dirname(__FILE__)."/mail/class.phpmailer.php"); 
 $array =  array_unique(Get_value('mail',1));
 $type = Get_value('type',1);

 
 $mail = new PHPMailer(); 
 $count =0; 
 $bad =0;
 $mail->IsSMTP();                                      // set mailer to use SMTP
 $mail->Host = "smtp.163.com";  // smtp1.example.com;smtp2.example.comspecify main and backup server
 $mail->SMTPAuth = true;     // turn on SMTP authentication
 $mail->Username = "mailangel123";  // SMTP username
 $mail->Password = "******"; // SMTP password
 
 $mail->From = "mailangel123@163.com";
 $mail->FromName = "你的好友来信";
 $MailBody = GetContent($type);

 //$array =explode('|',$rs['mail']);
 foreach( $array as $tmpmail ){
  if( @preg_match("/w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*/",$tmpmail)
   || strlen($User_Mail)<6 )
  {
   $mail->AddReplyTo("mailangel123@163.com", "44");
   $mail->AddAddress($tmpmail,'您好!');
   $mail->WordWrap = 50;
   $mail->CharSet="GB2312";                                
   //$mail->AddAttachment("/var/tmp/file.tar.gz");       
   //$mail->AddAttachment("/tmp/image.jpg", "new.jpg");  
   $mail->IsHTML(true);                           
   
   $mail->Subject = "你的朋友邀请你一起合影!";
   $mail->Body    = $MailBody;
   
   if(!$mail->Send())
   {
      $bad++;
      $mail->ClearAddresses();  
      $mail->ClearAttachments();
     
   }
   else
   {
    $count++;
   }
  }
  ShowMsg("result:$count");
  
 }

下面这个文章是读取html 文档并进行html发送哦,
 
 function GetContent($type){
  if( $type )
  {
   if(file_exists('./mail_room.html') )
   {
    $content = file_get_contents( './mail_room.html');
   }
   else
   {
    ShowMsg('file can' read fail ');
   }
  }
  else
  {
   if( file_exists( './mail_person.html') )
   {
    $content = file_get_contents( './mail_person.html');
   }
   else
   {
    ShowMsg('person file read fail!');
   }
   
  }
  return $content;
 }
 
 
 /* echo "<script>alert('发关".$count."邮件成功');</script>"; */

?>
本站原创http://www.111cn.net 转载请注明

php自带了邮件发送函数,我们可以使用mail来进行发送邮件,下面我们就来看一个使用mail进行发邮件的实例教程吧。
 代码如下 复制代码

<?php
//定义边界线
$boundary = uniqid( "" );
//生成邮件头
$header = "From: $from Content-type: multipart/mixed;
boundary="$boundary" X-Mailer:PHP X-Priority:3";
//获取附件文件的MIME类型
$mimetype = mime_content_type('test.zip')
//获取附件文件的名字
$attach = 'test.zip'
//对附件文件进行编码和切分
$fp = fopen($attach, "r");
$content = fread($fp, filesize($attach));
$content = chunk_split( base64_encode($content) );
//生成邮件主体
$body ="
--$boundary
Content-type: text/plain; charset=iso-8859-1
Content-transfer-encoding: 8bit
$message
--$boundary
Content-Type: $mimeType; name=$filename
Content-Disposition: attachment; filename=$filename
Content-Transfer-Encoding: base64
$content
--$boundary--";
//发送邮件
mail( $to, $subject, $body, $header );
?>

好了下面我们来看看php发送邮件函数mail 教程,如果要使用mail函数能够正常使用我们还得配置php.ini里面的参数哦。

<?php
//定义边界线
$boundary = uniqid( "" );
//生成邮件头
$header = "From: $from Content-type: multipart/mixed;
boundary="$boundary" X-Mailer:PHP X-Priority:3";
//获取附件文件的MIME类型
$mimetype = mime_content_type('test.zip')
//获取附件文件的名字
$attach = 'test.zip'
//对附件文件进行编码和切分
$fp = fopen($attach, "r");
$content = fread($fp, filesize($attach));
$content = chunk_split( base64_encode($content) );
//生成邮件主体
$body ="
--$boundary
Content-type: text/plain; charset=iso-8859-1
Content-transfer-encoding: 8bit
$message
--$boundary
Content-Type: $mimeType; name=$filename
Content-Disposition: attachment; filename=$filename
Content-Transfer-Encoding: base64
$content
--$boundary--";
//发送邮件
mail( $to, $subject, $body, $header );
?>

转载请注明:www.111cn.net

[!--infotagslink--]

相关文章

  • 不打开网页直接查看网站的源代码

      有一种方法,可以不打开网站而直接查看到这个网站的源代码..   这样可以有效地防止误入恶意网站...   在浏览器地址栏输入:   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
  • php简单用户登陆程序代码

    php简单用户登陆程序代码 这些教程很对初学者来讲是很有用的哦,这款就下面这一点点代码了哦。 <center> <p>&nbsp;</p> <p>&nbsp;</p> <form name="form1...2016-11-25
  • PHP实现清除wordpress里恶意代码

    公司一些wordpress网站由于下载的插件存在恶意代码,导致整个服务器所有网站PHP文件都存在恶意代码,就写了个简单的脚本清除。恶意代码示例...2015-10-23
  • JS实现双击屏幕滚动效果代码

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

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

    一、日期减去天数等于第二个日期function cc(dd,dadd){//可以加上错误处理var a = new Date(dd)a = a.valueOf()a = a - dadd * 24 * 60 * 60 * 1000a = new Date(a)alert(a.getFullYear() + "年" + (a.getMonth() +...2015-11-08
  • PHP开发微信支付的代码分享

    微信支付,即便交了保证金,你还是处理测试阶段,不能正式发布。必须到你通过程序测试提交订单、发货通知等数据到微信的系统中,才能申请发布。然后,因为在微信中是通过JS方式调用API,必须在微信后台设置支付授权目录,而且要到...2014-05-31
  • PHP常用的小程序代码段

    本文实例讲述了PHP常用的小程序代码段。分享给大家供大家参考,具体如下:1.计算两个时间的相差几天$startdate=strtotime("2009-12-09");$enddate=strtotime("2009-12-05");上面的php时间日期函数strtotime已经把字符串...2015-11-24
  • NodeJS实现阿里大鱼短信通知发送

    本文给大家介绍的是nodejs实现使用阿里大鱼短信API发送消息的方法和代码,有需要的小伙伴可以参考下。...2016-01-20
  • php怎么用拼音 简单的php中文转拼音的实现代码

    小编分享了一段简单的php中文转拼音的实现代码,代码简单易懂,适合初学php的同学参考学习。 代码如下 复制代码 <?phpfunction Pinyin($_String...2017-07-06
  • PHP测试成功的邮件发送案例

    mail()函数的作用:连接到邮件服务器,利用smtp协议,与该服务器交互并投邮件。注意:1、mail函数不支持esmtp协议,---即,只能直投,不能登陆2、由上条,我们只能直投至最终的收件服务器地址.而该地址,又是在PHP.ini中指定的,所...2015-10-30
  • php导出csv格式数据并将数字转换成文本的思路以及代码分享

    php导出csv格式数据实现:先定义一个字符串 存储内容,例如 $exportdata = '规则111,规则222,审222,规222,服2222,规则1,规则2,规则3,匹配字符,设置时间,有效期'."/n";然后对需要保存csv的数组进行foreach循环,例如复制代...2014-06-07
  • ecshop商品无限级分类代码

    ecshop商品无限级分类代码 function cat_options($spec_cat_id, $arr) { static $cat_options = array(); if (isset($cat_options[$spec_cat_id]))...2016-11-25
  • 几种延迟加载JS代码的方法加快网页的访问速度

    本文介绍了如何延迟javascript代码的加载,加快网页的访问速度。 当一个网站有很多js代码要加载,js代码放置的位置在一定程度上将会影像网页的加载速度,为了让我们的网页加载速度更快,本文总结了一下几个注意点...2013-10-13
  • php邮件发送的两种方式

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