This question already has an answer here:
Making a PHP script that also has a text file included as attachment. It works perfectly when I send to a GMAIL-address, but when I send to an address located at another web hoster, I can see that the file is attached, but when I open it, the file is empty (no content)... What can cause this?? This is the code I use:
$filename = basename($dirfilename);
$body = "File is included in mail";
$path = "downloads/";
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);
$eol = PHP_EOL;
// Headers
$header = "From: ".$from_name." <".$from_mail.">".$eol;
$header .= "Reply-To: ".$replyto.$eol;
$header .= "MIME-Version: 1.0
";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"";
// Message
$message = "--".$uid.$eol;
$message .= "Content-Type: text/html; charset=UTF-8".$eol;
$message .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$message .= $body.$eol;
$message .= "--".$uid.$eol;
$message .= "Content-Type: text/plain; name=\"".$filename."\"".$eol;
$message .= "Content-Transfer-Encoding: base64".$eol;
$message .= "Content-Disposition: attachment;
filename*=utf-8''" . rawurlencode($filename).$eol;
$message .= $content.$eol;
$message .= "--".$uid."--";
if (mail($mail_to, $subject, $message, $header))
{
echo "File sent";
} else {
echo "Fail";
}
</div>
If you look at a raw email:
--_004_8b72e1a6b3f242208a89b3fa9240bcf3avode_
Content-Type: application/pdf; name="TA1_031_21204-2.pdf"
Content-Description: TA1_031_20181204-2.pdf
Content-Disposition: attachment; filename="TA1_031_21204-2.pdf";
size=230847; creation-date="Mon, 10 Dec 2018 11:33:32 GMT";
modification-date="Mon, 10 Dec 2018 09:44:35 GMT"
Content-Transfer-Encoding: base64
JVBERi0xLjUNJeLjz9MNCjI4MDYgMCBvYmoNPDwvTGluZWFyaXplZCAxL0wgMjMwODQ3L08gMjgw
OC9FIDMzOTcvTiAyOC9UIDIzMDE2NS9IIFsgNDY3IDM0NF0+Pg1lbmRvYmoNICAgICAgICAgICAg
DQoyODEyIDAgb2JqDTw8L0RlY29kZVBhcm1zPDwvQ29sdW1ucyA0L1ByZWRpY3RvciAxMj4+L0Zp
bHRlci9GbGF0ZURlY29kZS9JRFs8MDU4QTRCNjk5OEFDNzE0M0JCRUZEMDFENjJCOEE5ODg+PDZG
Q0FDM0U1RTAyOTNDNDU5QzE2MkQzMTczMjM5RTYyPl0vSW5kZXhbMjgwNiAxM10vSW5mbyAyODA1
By the way you are composing your email
$message .= "Content-Disposition: attachment;
filename*=utf-8''" . rawurlencode($filename).$eol;
you are adding an unnecessary ' ' and no $eol in front of your file content.
Try something like:
$message .= 'Content-Disposition: attachment; filename=". rawurlencode($filename).";'.$eol.$eol;
But this will automatically done by PHPMailer.