Web DevelopmentPHP Email With Attachment

PHP Email With Attachment

How to send an email with an attachment in PHP


//email details ( change accordingly)
$to = "to-email-address@domain.com";
$from = "from-email-address@domain.com";
$subject = "Test Email with an attached file";
$message = "<p>Test Email - Check if the file is attached properly</p>";

//select a random hash to send MIME content
$hash = md5(time());

//carriage return type

//attachment name ( this name will be used to name the attachment file - may be different from the original filename )
$filename = "attach_file.pdf";

//encode data to correct format - read the attachment file and then encode it
$file = fopen( "path-to-original-file", 'rb' );
$attachment = fread( $file, filesize( $filename ) );
fclose( $file );
$attachment = chunk_split(base64_encode($attachment));

//main header (multipart mandatory)
$headers  = "From: ".$from.$EOL;
$headers .= "MIME-Version: 1.0".$EOL;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$hash."\"".$EOL.$EOL;
$headers .= "Content-Transfer-Encoding: 7bit".$EOL;
$headers .= "This is a MIME encoded message.".$EOL.$EOL;

$headers .= "--".$hash.$EOL;
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"".$EOL;
$headers .= "Content-Transfer-Encoding: 8bit".$EOL.$EOL;
$headers .= $message.$EOL.$EOL;

$headers .= "--".$hash.$EOL;
$headers .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$EOL;
$headers .= "Content-Transfer-Encoding: base64".$EOL;
$headers .= "Content-Disposition: attachment".$EOL.$EOL;
$headers .= $attachment.$EOL.$EOL;
$headers .= "--".$hash."--";

//send message
mail($to, $subject, "", $headers);

Categories: Web Development


  1. October 31, 2014 8:38 am

    career center resume help PHP Email With Attachment | Naveen S Nayak's Blog

Post a comment

Your email address will not be published. Required fields are marked *