我有一个我正在创建的文件,如下所示:
// Create and save the string on the file system
$str = "Business Plan: \nSome more text";
$fp = fopen("alex.txt", 'w+');
fwrite($fp, $str);
// email with the attachment
$to = 'alex.genadinik@gmail.com';
$subject = 'Your business plan attached';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: BusinessPlanApp@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('alex.txt')));
$contents = "some contents of the email";
mail($to, $subject, $contents, $headers);
该文件正在保存到文件系统中,并且正在通过正确的正文和主题向我发送电子邮件。
唯一出错的是附件是零字节的未命名文件。知道为什么会这样吗?这是权限问题吗?或者我的电子邮件中有什么东西?
谢谢!
答案 0 :(得分:3)
您将mime数据放入$attachment
,但之后不要在任何地方使用该变量,因此您实际上并未附加任何内容。
您最好使用PHPMailer或Swiftmailer等库来为您执行此操作。它不那么麻烦,它们可以在出现问题时为FAR提供更好的诊断。
答案 1 :(得分:2)
您的电子邮件代码似乎缺少一些东西。我开始修复它,但从头开始可能会更好。我推荐一个库,但如果没有,下面的代码应该达到你想要的效果:
// Create and save the string on the file system
$str = "Business Plan: \nSome more text";
$fp = fopen("alex.txt", 'w+');
fwrite($fp, $str);
fclose($fp);
// email fields: to, from, subject, and so on
$from = "BusinessPlanApp@example.com";
$to = 'alex.genadinik@gmail.com';
$subject = 'Your business plan attached';
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// message text
$contents = "This is the email content";
// multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $contents. "\n\n";
// preparing attachments
$message .= "--{$mime_boundary}\n";
$fp = fopen('alex.txt',"rb");
$data = fread($fp,filesize('alex.txt'));
fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename('alex.txt')."\"\n" .
"Content-Description: ".basename('alex.txt')."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename('alex.txt')."\"; size=".filesize('alex.txt').";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}--";
mail($to, $subject, $message, $headers);