2011-01-27 165 views
0

我已经实现了一个PHP邮件函数,用于发送带有附件的邮件,但是我正在接收带有0 kb附件的邮件。我使用的代码如下:php - 带附件的邮件

<?php 
$fileatt = ""; // Path to the file 
$fileatt_type = "application/octet-stream"; // File Type 
$fileatt_name = ""; // Filename that will be used for the file as the attachment 

$email_from = ""; // Who the email is from 
$email_subject = ""; // The Subject of the email 
$email_txt = ""; // Message that the email has in it 

$email_to = ""; // Who the email is too 

$headers = "From: ".$email_from; 

$file = fopen($fileatt,'rb'); 
$data = fread($file,filesize($fileatt)); 
fclose($file); 

$semi_rand = md5(time()); 
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 

$headers .= "\nMIME-Version: 1.0\n" . 
"Content-Type: multipart/mixed;\n" . 
" boundary=\"{$mime_boundary}\""; 

$email_message .= "This is a multi-part message in MIME format.\n\n" . 
"--{$mime_boundary}\n" . 
"Content-Type:text/html; charset=\"iso-8859-1\"\n" . 
"Content-Transfer-Encoding: 7bit\n\n" . 
$email_message . "\n\n"; 

$data = chunk_split(base64_encode($data)); 

$email_message .= "--{$mime_boundary}\n" . 
"Content-Type: {$fileatt_type};\n" . 
" name=\"{$fileatt_name}\"\n" . 
//"Content-Disposition: attachment;\n" . 
//" filename=\"{$fileatt_name}\"\n" . 
"Content-Transfer-Encoding: base64\n\n" . 
$data . "\n\n" . 
"--{$mime_boundary}--\n"; 

$ok = @mail($email_to, $email_subject, $email_message, $headers); 

if($ok) { 
echo "<font face=verdana size=2>The file was successfully sent!</font>"; 
} else { 
die("Sorry but the email could not be sent. Please go back and try again!"); 
} 
?> 

我找不出这个代码的问题。请任何人帮助我!

+0

看不到问题;检查你的垃圾邮件文件夹 – arnaud576875 2011-01-27 11:46:48

+0

除了使用像phpmailer(http://phpmailer.worxware.com/)这样的库之外,如果你在发送之前打印变量$ email_message的内容呢?你确定你阅读完整的文件吗?如何看你的标题? – keatch 2011-01-27 11:49:05

回答

4

也许我是个理想主义的傻瓜,但是PHP的mail()函数有问题困扰,而且看起来总是如此。

我倾向于建议所有新项目都使用邮件库,例如Swiftmailer(或类似),因为它们倾向于处理边缘案例比滚动你自己的更好,并且它们已经过更广泛的测试反对可能会邮寄的奇怪事物。

除了PHP本身包含的PHP库外,还有大量的PHP库可用,许多框架还提供Mail类。它已经到了使用框架和库产生更坚固的应用程序的地步,而不是重新发明许多轮子,并且自己动手去做所有事情。