i have this php code that allows for an attachment to emails. this works, the email is sent and the attachment is there, but when I open the attachment its empty. i’m attaching a word.doc. I’ve spent hours on google without resolving this. anyone please any ideas??
$to = "xxxx@hotmail.com";
$from = "xxxx@xxxx";
$subject = "subject";
$message = "message is this";
$fileatt = $_FILES['strresume']['tmp_name'];
$fileatt_type = $_FILES['strresume']['type'];
$fileatt_name = $_FILES['strresume']['name'];
$headers = "From: $from";
if (is_uploaded_file($fileatt)) {
// Read the file to be attached ('rb' = read binary)
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
// Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Add the headers for a file attachment
$headers .= "\
MIME-Version: 1.0\
" .
"Content-Type: multipart/mixed;\
" .
"boundary=\\"{$mime_boundary}\\"";
// Add a multipart boundary above the plain message
$message = "This is a multi-part message in MIME format.\
\
" .
"--{$mime_boundary}\
" .
"Content-Type: text/plain; charset=\\"iso-8859-1\\"\
" .
"Content-Transfer-Encoding: 8bit\
\
" .
$message . "\
\
";
// Base64 encode the file data
$data = chunk_split(base64_encode($data));
// Add file attachment to the message
$message .= "--{$mime_boundary}\
" .
"Content-Type: {$fileatt_type};\
" .
" name=\\"{$fileatt_name}\\"\
" .
"Content-Disposition: attachment;\
" .
" filename=\\"{$fileatt_name}\\"\
" .
"Content-Transfer-Encoding: base64\
\
" .
$data . "\
\
" .
"--{$mime_boundary}--\
";
}
// Send the message
$ok = @mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>Mail sent! Yay PHP!</p>";
} else {
echo "<p>Mail could not be sent. Sorry!</p>";
}
}
I had the same problem a while back and it turned out to be the first and second boundary names. Both can have the same hash code but they need to be named differently, so one could be called ‘b1_’ and the other ‘b2_’.
I have spent the whole day trying to understand why it was not working and the reson it was not was because it never created the temporary file so for it to be attached in the mailing, so I changed this:
Instead of trying to craft the e-mail yourself, it might be easier to use an existing library for sending the mail & attachment. See this thread for some more info: http://www.sitepoint.com/forums/showthread.php?t=700610