我使用mail()
函数来测试发送带有图像文件附件的电子邮件给我自己。这个脚本的问题是,当我查看电子邮件时,我看到了一长排随机数字、字母和符号,而这些本来应该是图像。
请不要推荐PHPmailer或在消息正文中手动放置图像标签。
我使用的主PHP文件:
<?
include('init.php');
if (isset($_POST['name'], $_FILES['file'])){
$body = <<<BODY
From: {$_POST['name']}
Details:
Name: {$_FILES['file']['name']}
Size: {$_FILES['file']['size']}
Type: {$_FILES['file']['type']}
BODY;
mail_file('receiver@email.com','test@php.com','a file upload',$body,$_FILES['file']);
}
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="text" name="name" id="name">
<input type="file" name="file" id="file">
<input type="submit" value="Email File">
</form>
init.php:
<?
$path = dirname(__FILE__);
include("{$path}/mail.php");
?>
mail.php:
<?
function mail_file($to, $from, $subject, $body, $file){
$boundary = md5(rand());
$headers = array(
'MIME-Version: 1.0',
"Content-Type: multipart/mixed; boundary="{$boundary}"",
"From: {$from}"
);
$message = array(
"--{$boundary}",
'Content-Type: text/html',
'Content-Transfer-Encoding: 7bit',
'',
chunk_split($body),
"--{$boundary}",
"Content-Type: {$file['type']}; name="{$file['name']}"",
"Content-Disposition: attachment; name="{$file['name']}"",
"Content-Transfer-Encoding: base64",
'',
chunk_split(base64_encode(file_get_contents($file['tmp_name']))),
"--{$boundary}--"
);
mail($to, $subject, implode('rn', $message), implode('rn', $headers));
}
?>
发送的电子邮件示例:
--4f8b4f63eb5fb4f1c3cde903c7e5b306rnContent-Type: text/htmlrnContent-Transfer-Encoding: 7bitrnrn From: asas
Details:
Name: 728x90-Brink-Banner-V2.jpg
Size: 41583
Type: image/jpeg
rn--4f8b4f63eb5fb4f1c3cde903c7e5b306rnContent-Type: image/jpeg; name="728x90-Brink-Banner-V2.jpg"rnContent-Disposition: attachment; name="728x90-Brink-Banner-V2.jpg"rnContent-Transfer-Encoding: base64rnrn/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAAUAAA/+4ADkFkb2JlAGTAAAAAAf/b
AIQAAgICAgICAgICAgMCAgIDBAMCAgMEBQQEBAQEBQYFBQUFBQUGBgcHCAcHBgkJCgoJCQwMDAwM
DAwMDAwMDAwMDAEDAwMFBAUJBgYJDQsJCw0PDg4ODg8PDAwMDAwPDwwMDAwMDA8MDAwMDAwMDAwM
DAwMDAwMDAwMDAwMDAwMDAwM/8AAEQgAWgLYAwERAAIRAQMRAf/EAOgAAAAGAwEAAAAAAAAAAAAA
AAMEBQYHCAECCQABAAAHAQEBAAAAAAAAAAAAAAABAgMEBQYHCAkQAAEDAgUBBgMDBAsHDA0NAQEC
...
L81/7CT7TfOuj+7T/wCxbf6cmeeXwouVG4P5we/F/E/yvzHTHMh6q9MNzUc7m/T5X4f4h6fP+6uF
jIJbcyh7Z0b6/h/d6fbhYSHp7D+cIXk/RYHy/RU9P+y/j6sIk9VBmYV1+H+sf9B6Dz+b7cZufPat
RB6oyV2LP+B/6NfhD8X8X7Ph34OPJMy+so95T/RGP/NzzD+bfxuuFyeoozf1ozUXWfoz+n/jJ/Rv
P9n8XvxTvzWktcx8eSvxxR+Gn9P6p83k7Ov72JFl4VE1T1tngUtb2/mmd+H+iu/jfyD1xZyZKqhz
VHdz/wA4H9F/Aa6/h/oKPxP+y+GKmX4eNXtuv//Z
rn--4f8b4f63eb5fb4f1c3cde903c7e5b306--
问题出在这里:
mail($to, $subject, implode('rn', $message), implode('rn', $headers));
您使用了单引号,新行被视为4个字符的字符串rn
,将其更改为:
mail($to, $subject, implode("rn", $message), implode("rn", $headers));