tags:

views:

392

answers:

1

I am sending an email using PHP mail() and I can successfully receive and open the attachment (in this case a pdf) in almost every program i have access to. Except in mac mail where I am told that the file is corrupt. Has anyone else run into this problem before? Below is the script I am using:

//define the receiver of the email
$to = '[email protected]';
//define the subject of the email
$subject = 'Email with Attachment';
//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: base64\n";
$message .= "\n";
$message .= "Email content and what not: \n";
$message .= "This is the file you asked for! \n";
$message .= "--".$mime_boundary."" . "\n";

$message .= "Content-Type: application/octet-stream;\n";
$message .= " name=\"CTF-brochure.pdf\"" . "\n";
$message .= "Content-Transfer-Encoding: base64 \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";

Thanks in advance!

A: 

No idea what's going on there, but I'm always surprised how many people try to roll their own mail-construction code.

Have you considered just using a library like SwiftMailer or PHPMailer? In almost every situation, you'll get better formatting, fewer headaches, and often better performance.

timdev
thanks for this but if i use those, i will never learn how to Build a better one. Plus i have tried several different varieties and none of them work on this server.
Drew