This is a part of a simple mail sending script from PHP. It does create a PDF attachment from FPDF (code is not included here) + it adds some more user uploaded attachments.
If I remove $message
from $mail_sent = @mail( $to, $subject, $message, $body, $headers );
, it sends the attachments just fine, but if put the $message
back in $mail_sent
, it seems to get mixed up with the attachments and it leaves a large chunk of text in the mail. I guess it has something to do with MIME boundaries, but I just can't figure out where the problem lies.
Any help would be much appreciated.
<?php
$to = "[email protected]";
$from = $_POST["[email protected]"];
$subject = "Subject";
$message = "This is the message";
$eol = PHP_EOL;
$filename = "$filename.pdf";
$pdfdoc = $pdf->Output("", "S");
$attachment = chunk_split(base64_encode($pdfdoc));
$fileatt_name = isset($_POST['fileatt_name']) ? $_POST['fileatt_name'] : '';
// Header
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
$headers = "From: $from\r".$eol .
$headers = "Bcc: ".$bcc."\r".$eol .
"MIME-Version: 1.0\r".$eol .
"Content-Type: multipart/mixed;\r".$eol .
" boundary=\"{$mime_boundary}\"";
$body = "This is a multi-part message in MIME format.".$eol.$eol .
"--{$mime_boundary}".$eol .
"Content-Type: text/plain; charset=\"iso-8859-1\"".$eol .
"Content-Transfer-Encoding: 7bit".$eol.$eol .
"".$eol.$eol;
// PDF-Attachment
$body .= "--{$mime_boundary}".$eol;
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol;
$body .= "Content-Transfer-Encoding: base64".$eol;
$body .= "Content-Disposition: attachment".$eol.$eol;
$body .= $attachment.$eol;
$body.="--{$mime_boundary}--".$eol;
// More attachments
foreach($_FILES as $userfile)
{
$tmp_name = $userfile['tmp_name'];
$type = $userfile['type'];
$name = $userfile['name'];
$size = $userfile['size'];
if (file_exists($tmp_name))
{
if(is_uploaded_file($tmp_name))
{
$file = fopen($tmp_name,'rb');
$data = fread($file,filesize($tmp_name));
fclose($file);
$data = chunk_split(base64_encode($data));
}
$body .= "--{$mime_boundary}".$eol .
"Content-Type: {$type};".$eol .
" name=\"{$name}\"".$eol .
"Content-Disposition: attachment;".$eol .
" filename=\"{$fileatt_name}\"".$eol .
"Content-Transfer-Encoding: base64".$eol.$eol .
$data . "".$eol.$eol;
}
}
// Send
$mail_sent = @mail( $to, $subject, $message, $body, $headers );
echo $mail_sent ? "Success" : "Failed";
?>
Resolved by adding $body .= $message.$eol;
before the PDF-attachment.