Home > Web Development > PHP 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. No comments yet.
  1. October 31, 2014 at 8:38 AM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: