zen-cart网站,模版,采集,二次开发

首页 » Linux » PHP » 阅读文章

php发送带附件的Email

2011-05-17 11:36 28756 0 发表评论
标签:


示例

静态页index.html

<html>
<body>
<form method=post name=sndml 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=text ></td>
</tr>
<tr ><td>源数据文件:</td>
<td><input type=file name=upload_file size=40></td>
</tr>
<tr><td>&nbsp</td>
<td><input type="submit" value="确定">
</td>
</tr>
</table>
</form>
</body>
</html>

sendmail.php

<?php
//文本内容
$text = $_POST['text'];
//标题
$subject = $_POST['subject'];
//发送者
$from = $_POST['from'];
//接受者
$to = $_POST['to'];
//附件
$file = $_FILES['upload_file']['tmp_name'];
// 定义分界线
$boundary = uniqid( "");
$headers = "Content-type: multipart/mixed; boundary= $boundary\r\n";
$headers .= "From:$from\r\n";
//确定上传文件的MIME类型
if($_FILES['upload_file']['type'])
$mimeType = $_FILES['upload_file']['type'];
else
$mimeType ="application/unknown";
//文件名
$fileName = $_FILES['upload_file']['name'];

// 打开文件
$fp = fopen($file, "r");
// 把整个文件读入一个变量
$read = fread($fp, filesize($file));
//我们用base64方法把它编码
$read = base64_encode($read);
//把这个长字符串切成由每行76个字符组成的小块
$read = chunk_split($read);
//现在我们可以建立邮件的主体
$body = "--$boundary
Content-type: text/plain; charset=iso-8859-1
Content-transfer-encoding: 8bit
$text
--$boundary
Content-type: $mimeType; name=$fileName
Content-disposition: attachment; filename=$fileName
Content-transfer-encoding: base64
$read
--$boundary--";
//发送邮件
if(mail($to, $subject,$body,$headers))
print "OK! the mail $from --- $to has been send<br>";
else
print "fail to send mail <br>";
?>

说明:

1.邮件头的构造 :一般包括

内容类型(Content-type)要发送附件,设置为 multipart/mixed 意思是多个部分 (邮件本身+附件)。

boundary ,就是上面提到的分界线,他的值用php自带的 uniqid();函数取得

接受方,抄送等,在后面加上 From: Cc:。与上面的 Content-type boundary 之间用 \r\n 分割 。

2 .邮件体

如果是纯文本的邮件内容 它的格式如下:

Content-type: text/plain; charset=iso-8859-1

Content-transfer-encoding: 8bit

后面再紧接着加上 邮件的文本内容。

3.附件:

Content-type: $mimeType; name=$fileName

Content-disposition: attachment; filename=$fileName

Content-transfer-encoding: base64

后面再紧接着加上 附件内容。

$mimeType 是附件的 MIME类型。 可以用 $_FILES['upload_file']['type'] 得到。

$fileName 就是附件的名字了

邮件文本内容和附件之间用 boundary 分割。

附件内容就是用read函数读入所上传的附件,然后再把它经过base64编码之后再用chunk_split 大卸N块,每块大小是默认的76字符。

示例下载:http://dl.dbank.com/c039itqd4k

随机日志

评论 共0条 (RSS 2.0) 发表评论

  1. 暂无评论,快抢沙发吧。

发表评论

  • 
  • 插入代码

联系我 Contact Me

回到页首