php简单实现发送带附件的邮件

yipeiwu_com6年前PHP代码库

本文实例讲述了php简单实现发送带附件的邮件。分享给大家供大家参考。具体如下:

下面是静态html代码:

<html>
 <head>
 <title>带附件的邮件发送</title>
 </head>
 <body> 
 <form method="post" name="form1" action="sendmail.php" ENCTYPE="multipart/form-data"> 
  <table> 
  <tr>
   <td>发送人:</td> 
   <td><input type="text" name="from"></td> 
  </tr> 
  <tr>
   <td>收件人:</td> 
   <td><input type="text" name="to"></td> 
  </tr> 
  <tr>
   <td>邮件主题:</td> 
   <td><input type="text" name="subject"></td> 
  </tr> 
  <tr>
   <td>邮件内容:</td> 
   <td><textarea name="body"></textarea></td> 
  </tr> 
  <tr>
   <td>附件上传:</td> 
   <td><input type="file" name="upload_file"></td> 
  </tr> 
  <tr> 
   <td span=2>
   <input type="submit" value="提交"> 
   <input type="reset" value="重置"> 
   </td> 
  </tr> 
  </table> 
 </form> 
 </body> 
</html>

sendmail.php文件代码:

<?php  
//获得表单信息 
$from = $_POST['from']; 
$to = $_POST['to'];  
$subject = $_POST['subject'];  
$body = $_POST['body'];  
// 定义分界线  
$boundary = "345894369383"; //分界线是一串无规律的字符 
//设置header 
$header = "Content-type: multipart/mixed; boundary= $boundary/r/n";  
$header .= "From:$from/r/n";  
//获得上传文件的文件内容 
$file = $_FILES['upload_file']['tmp_name'];  
//确定上传文件的MIME类型  
$mimeType = $_FILES['upload_file']['type'];  
//获得上传文件的文件名  
$fileName = $_FILES['upload_file']['name'];  
//读取上传文件  
$fp = fopen($file, "r"); //打开文件 
$read = fread($fp, filesize($file)); //读入文件 
$read = base64_encode($read); //base64编码  
$read = chunk_split($read); //切割字符串 
//建立邮件的主体,分为邮件内容和附件内容两部分 
$body = "--$boundary  
Content-type: text/plain; charset=iso-8859-1  
Content-transfer-encoding: 8bit  
$body  
--$boundary  
Content-type: $mimeType; name=$fileName  
Content-disposition: attachment; filename=$fileName  
Content-transfer-encoding: base64  
$read  
--$boundary--";  
//发送邮件 并输出是否发送成功的信息 
if(mail($to, $subject,$body,$header))  
{ 
  echo "信件发送成功";  
} 
else  
{ 
  echo "信件发送失败";  
} 
?>

希望本文所述对大家的php程序设计有所帮助。

相关文章

PHP安装memcached扩展笔记

PHP安装memcached扩展笔记

最近在服务器上部缓存系统,记录一下PHP安装memcached扩展。 复制代码 代码如下: # 安装服务端 yum install memcached -y I. launchpad...

php上的memcache和memcached两个pecl库

之前尝试用的是memcache,后来发现memcached支持setMulti方法,准备转向使用memcached库了。 (试了下,实际上,memcache从支持多值set,但文档上还没...

仿AS3实现PHP 事件机制实现代码

复制代码 代码如下: <?php /** * 事件异常 * * @author lonely * @create 2010-10-21 * @version 0.1 * @last...

php计算一个文件大小的方法

本文实例讲述了php计算一个文件大小的方法。分享给大家供大家参考。具体如下: <?php function dirSize($directoty){ $di...

php park、unpark、ord 函数使用方法(二进制流接口应用实例)

php park、unpark、ord 函数使用方法(二进制流接口应用实例)

park,unpark,ord这3个函数,在我们工作中,用到它们的估计不多。 我在最近一个工作中,因为通讯需要用到二进制流,然后接口用php接收。当时在处理时候,查阅不少资料。因为它们使...