// 打开文件 $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 之间用 rn 分割 。 2 邮件体 如果是纯文本的邮件内容 它的格式如下: Content-type: text/plain; charset=iso-8859-1 Content-transfer-encoding: 8bit 后面再紧接着加上 邮件的文本内容。 如果是附件: 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字符。 好了,现在再去看那段程序,应该没什么问题了吧?把相应的变量带入mail函数里面就ok了。 以上程序在 PHP Version 4.3.8 freeBSD 下测试通过。 参考文章:《php 发送带附件的邮件 作者: cn-linux》
(编辑:焦作站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|