PHP群发邮件脚本在outlook中显示额外的文件


PHP mass mail script shows extra file in outlook

我使用PHP脚本发送带有多个附件的电子邮件,它适用于gmail,但在Microsoft Outlook中,我也看到空白文件ATT00010.txt(随机数)作为附件。当我从outlook发送带有多个附件的电子邮件时,它也不会显示没有这样的文件。

我从电子邮件脚本回显输出,代码中没有这样的文件。有人能告诉我如何从outlook中删除这个文件吗?

邮件脚本如下。

// array with filenames to be sent as attachment
$files = array("file_1.ext","file_2.ext","file_3.ext",......);
// email fields: to, from, subject, and so on
$to = "mail@mail.com";
$from = "mail@mail.com"; 
$subject ="My subject"; 
$message = "My message";
$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}'""; 
// multipart boundary 
$message = "This is a multi-part message in MIME format.'n'n" . "--{$mime_boundary}'n" . "Content-Type: text/plain; charset='"iso-8859-1'"'n" . "Content-Transfer-Encoding: 7bit'n'n" . $message . "'n'n"; 
$message .= "--{$mime_boundary}'n";
// preparing attachments
for($x=0;$x<count($files);$x++){
    $file = fopen($files[$x],"rb");
    $data = fread($file,filesize($files[$x]));
    fclose($file);
    $data = chunk_split(base64_encode($data));
    $message .= "Content-Type: {'"application/octet-stream'"};'n" . " name='"$files[$x]'"'n" . 
    "Content-Disposition: attachment;'n" . " filename='"$files[$x]'"'n" . 
    "Content-Transfer-Encoding: base64'n'n" . $data . "'n'n";
    $message .= "--{$mime_boundary}'n";
}
// send
$ok = @mail($to, $subject, $message, $headers); 
if ($ok) { 
    echo "<p>mail sent to $to!</p>"; 
} else { 
    echo "<p>mail could not be sent!</p>"; 
} 

如果你想要一些使用和发送附件更少痛苦的东西,试试Swift Mailer。(swiftmailer.org)我一直在我的项目中使用它,它工作得很好。

下面是一个例子:

$message = Swift_Message::newInstance()
  ->setSubject('Webinar Registration')
  ->setFrom(array('replyto@example.org' => 'From Name'))
  ->setTo(array('destination@example.org'))
  ->setBody($MESSAGE_TEXT)
  ;
$message->attach(Swift_Attachment::fromPath('SOME_FILE_PATH'));
$transport = Swift_SmtpTransport::newInstance('127.0.0.1', 25);
$mailer = Swift_Mailer::newInstance($transport);
$result = $mailer->send($message);

只是我的两分钱。

否则,我就会提到别人已经抢先我一步的事情——检查边界。

multipart/*消息中的最后一个边界线必须在末尾附加-- ,除了所有其他边界线具有的内容。消费者可以使用它来识别消息的结尾。

显然Outlook将缺少正确的结尾视为消息已被截断的指示,然后尽其所能显示它收到的内容

这是我的第二个帐户,我实际上找到了解决方案,根本不需要库或类,尽管我可能会把它变成类并添加一些东西,它总是更好地充分理解过程,而不仅仅是from, to, files等字段。

解决方法很简单,只需将最后一部分替换为

    if ($x == count($files)-1) 
        $message .= "--{$mime_boundary}--'r'n";
    else
        $message .= "--{$mime_boundary}'n";

'r不需要

如果你只是——它会在循环内多次使用它if检查这是否是最后一个循环。