PHP发送带附件邮件

PHP发送带附件邮件

用PHP内置的mail函数,通过添加邮件header头,发送附件。

代码:


<?php

// 发件人
$from = 'mogu';
// 收件人
$to = 'mogu@126.com';
// 主题
$subject = 'subject';
// 附件
$files = array('1.jpg');
// 消息
$message = 'adfasdf';

// 邮件头
$headers .= "From: $fromnMIME-Version: 1.0nContent-Type: multipart/mixed;n boundary="d414c0ec4a56e42e2e2e9dfd4061de39"";

// 消息
$message = "--d414c0ec4a56e42e2e2e9dfd4061de39nContent-Type: text/plain; charset="iso-8859-1"nContent-Transfer-Encoding: 7bitnn$messagenn";
foreach($files as $v){
	if(is_file($v)){
		$message .= "--d414c0ec4a56e42e2e2e9dfd4061de39n";
		$data = file_get_contents($v);
		$data = chunk_split(base64_encode($data));
		$message .= "Content-Type: application/octet-stream; name="".basename($v).""n" .
		"Content-Description: ".basename($v)."n" .
		"Content-Disposition: attachment;n" . " filename="".basename($v).""; size=".filesize($v).";n" .
		"Content-Transfer-Encoding: base64nn" . $data . "nn";
	}
}
$message .= "--d414c0ec4a56e42e2e2e9dfd4061de39--";

// 发送邮件
$ok = mail($to, $subject, $message, $headers);

var_dump($ok);


另一种写法:


<?php

// 发件人昵称
$from = '蘑菇';

// 收件人
$to = 'mogu@126.com';

// 主题
$subject = '主题';

// 内容
$message = '内容';

// 附件
$files = 'test.jpg';
$filesname = basename('test.jpg');
$filesize = filesize($files);

// 把附件进行base64转化
$data = chunk_split(base64_encode(file_get_contents($files)));

// 邮件header头
$headers = <<<EOK
From: $from
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="9b3373f3edca05ebae8a30498eda447b"
EOK;

// 邮件主体内容
$message = <<<EOK
--9b3373f3edca05ebae8a30498eda447b
Content-Type: text/plain; charset=GB2312
Content-Transfer-Encoding: 7bit

$message

--9b3373f3edca05ebae8a30498eda447b
Content-Type: application/octet-stream; name="$filesname"
Content-Description: $filesname
Content-Disposition: attachment; filename=$filesname; size=$filesize
Content-Transfer-Encoding: base64

$data

--9b3373f3edca05ebae8a30498eda447b--
EOK;

// 发送邮件
$ok = mail($to, $subject, $message, $headers);

var_dump($ok);

发表评论