0

我有一个像这样动态创建的文件:

// 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);

该文件正在保存到文件系统中,并且一封带有正确正文和主题的电子邮件正在发送给我。

唯一出错的是附件是零字节的未命名文件。知道为什么会发生这种情况吗?是权限问题吗?或者在我的电子邮件中?

谢谢!

4

2 回答 2

3

您将 mime 数据放入$attachment,但不要在任何地方使用该变量,因此您实际上并没有附加任何东西。

您最好使用诸如PHPMailerSwiftmailer 之类的库来为您执行此操作。它的麻烦要少得多,并且在出现问题时它们可以提供更好的诊断。

于 2012-05-19T18:40:23.577 回答
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);
于 2012-05-19T18:49:11.873 回答