使用PHP发送zip文件时出现空消息

时间:2014-11-29 14:11:54

标签: php

**更新:更新了代码并添加了Gmail中显示的电子邮件内容。 **

我有一个问题,我一直试图解决这几天。但由于我无法取得任何进展,我希望得到别人的帮助。我正在尝试从我的服务器发送一个zip文件到我的电子邮件。但是,电子邮件被发送为空。这是代码:

`$headers = "From: $from";
/* Generate boundary string */
$random = md5(time());
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random."\"";   
/* Read the file */
$attachment = chunk_split(base64_encode(file_get_contents("backup-$date-$time-9.zip")));
/* Define body */
$message = "--PHP-mixed-$random
Content-Type: text/plain; charset=\"iso-8859-1\"

Attached, please find your backup file. 

--PHP-mixed-$random
Content-Type: application/zip; name=backup-$date-$time-9.zip
Content-Transfer-Encoding: base64
Content-Disposition: attachment

$attachment

--PHP-mixed-$random--"; // no intendation
$mail = mail($email, $subject, $message, $headers);
echo $mail ? "Email sent<br>" : "Email sending failed<br>";`

感谢所有阅读并希望提供帮助。

Gmail中显示的结果电子邮件是

  

附上,请找到您的备份文件。

--PHP-mixed-e44b531b0e0538185289abc521eda78d
Content-Type: application/zip; name=backup-29-11-2014-1417275285-9.zip
Content-Transfer-Encoding: base64
Content-Disposition: attachment

UEsDBBQAAAAIAFZ8fUUs...sUEsFBgAAAAACAAIAeAAAAD4B

AAAAAA ==

--PHP-mixed-e44b531b0e0538185289abc521eda78d--

1 个答案:

答案 0 :(得分:2)

我通过以下更改来实现它:

  • 删除From:标题中的空格字符,否则为无效标题
  • boundary:更改为boundary=
  • 删除了$message中的意图,因为这似乎打破了电子邮件。边界字符串--PHP-mixed-random将电子邮件的不同部分分开,例如纯文本,html文本,彼此的附件。当边界分隔符前面有空格时,它不再被解释为分隔符,而是作为普通文本。

以下是代码:

<?php
$from = "xxx@myserver";
$email = "xxx@gmail.com";
$subject = "backup file";
$date = "29-11-2014";
$time = "1417275285"; // test file "backup-29-11-2014-1417275285-9.zip" in the same folder

$headers = "From: $from"; // remove space
/* Generate boundary string */
$random = md5(time());
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random."\""; // : to =
/* Read the file */
$attachment = chunk_split(base64_encode(file_get_contents("backup-$date-$time-9.zip")));
/* Define body */
$message = "--PHP-mixed-$random
Content-Type: text/plain; charset=\"iso-8859-1\"

Attached, please find your backup file. 

--PHP-mixed-$random
Content-Type: application/zip; name=backup-$date-$time-9.zip
Content-Transfer-Encoding: base64
Content-Disposition: attachment

$attachment

--PHP-mixed-$random--"; // no intendation
$mail = mail($email, $subject, $message, $headers);
echo $mail ? "Email sent<br>" : "Email sending failed<br>";