我正在使用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('\r\n', $message), implode('\r\n', $headers));
}
?>
发送电子邮件的示例:
--4f8b4f63eb5fb4f1c3cde903c7e5b306\r\nContent-Type: text/html\r\nContent-Transfer-Encoding: 7bit\r\n\r\n From: asas
Details:
Name: 728x90-Brink-Banner-V2.jpg
Size: 41583
Type: image/jpeg
\r\n--4f8b4f63eb5fb4f1c3cde903c7e5b306\r\nContent-Type: image/jpeg; name="728x90-Brink-Banner-V2.jpg"\r\nContent-Disposition: attachment; name="728x90-Brink-Banner-V2.jpg"\r\nContent-Transfer-Encoding: base64\r\n\r\n/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
\r\n--4f8b4f63eb5fb4f1c3cde903c7e5b306--
答案 0 :(得分:3)
问题出在这里:
mail($to, $subject, implode('\r\n', $message), implode('\r\n', $headers));
您使用了单引号,新行被视为4字符串\r\n
,将其更改为:
mail($to, $subject, implode("\r\n", $message), implode("\r\n", $headers));