Monday, June 16, 2008

Sending PDF as Attachment in Email Using PHP

$fileToSend = "myPDF.pdf"; //path to the PDF you want to send
$fileatttype = "application/pdf";
$file = fopen( $fileToSend, 'rb' );
$data = fread( $file, filesize( $fileToSend ) );
fclose( $file );

$semi_rand = md5( time() );
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

$headers = "FROM:From Address Goes HERE!";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$data = chunk_split( base64_encode( $data ) );

$messageBody="This will be the Body of the email!";

$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$messageBody. "\n\n";

$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileToSend}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileToSend}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";

//all set.. Now send the Email
mail ($email,"Subject Goes Here!",$message,$headers ) ;

No comments: