I have been struggling with trying to send an email with an attachment using PHP. It used to work but the message body was scrambled. Now I have got the message body to work but the attachment corrupts. I used to use base64 encoding for the message body but now use 7bit. Can anyone tell me what I am doing wrong?
PS please do not tell me that I should be using a pre-made class to do this. I have tried several and they have all failed to work. If I do not overcome these problems I will never learn how to do it properly. Thanks
//define the receiver of the email
$to = '[email protected]';
//define the subject of the email
$subject = 'Your Disneyland Paris entry';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \n
$mime_boundary = "<<<--==+X[".md5(time())."]";
$path = $_SERVER['DOCUMENT_ROOT'].'/two/php/';
$fileContent = chunk_split(base64_encode(file_get_contents($path.'CTF_brochure.pdf')));
$headers .= "From: [email protected] <[email protected]>"."\n";
$headers .= "MIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$message = "This is a multi-part message in MIME format.\n";
$message .= "\n";
$message .= "--".$mime_boundary."\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .= "Content-Transfer-Encoding: 7bit\n";
$message .= "\n";
$message .= "messagebody \n";
$message .= "--".$mime_boundary."" . "\n";
$message .= "Content-Type: application/octet-stream;\n";
$message .= " name=\"CTF-brochure.pdf\"" . "\n";
$message .= "Content-Transfer-Encoding: 7bit \n";
$message .= "Content-Disposition: attachment;\n";
$message .= " filename=\"CTF_brochure.pdf\"\n";
$message .= "\n";
$message .= $fileContent;
$message .= "\n";
$message .= "--".$mime_boundary."--\n";
//send the email
$mail_sent = mail($to, $subject, $message, $headers);
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";