send email with attachment file in PHP

how to send email with attachment file in PHP

In this post we will show you how to send email with attachment in php. by using this following code is used for send email with attachment in php. following code will sending pdf file in email.

$file_name = "example.pdf"; // attachment file name
$path = "folder_name"; // path of attachment file
$user_name = "user name"; // user name
$mail_to = "onlinecode@email.com"; // to eamil
$email_subject = "Notification of attachment for user"; // subject of eamil
$body_text = "Hello ".$user_name.",\nThis demo message with file attachment. You will be notified when their review has been completed.\n Regard \n onlinecode Team";

$attachment_file = $path . "/" . $file_name; // path of file
$attachment_file_size = filesize($attachment_file);
$email_handle = fopen($attachment_file, "r");
$content = fread($email_handle, $attachment_file_size);
fclose($email_handle);// file close of email handle
$content = chunk_split(base64_encode($content));
$time_separator = md5(time());// a random hash will be necessary to send mixed content

// carriage return type (we use a PHP end of line constant)
$email_eol = PHP_EOL;
$body_message = $body_text;
// main header (multipart mandatory)
$email_headers = "From: onlinecode Team <onlinecode@email.co>" . $email_eol;
// sender eamil detail
$email_headers .= "MIME-Version: 1.0" . $email_eol;//MIME-Version
$email_headers .= "Content-Type: multipart/mixed; boundary=\"" . $time_separator . "\"" . $email_eol;//Content-Type
$email_headers .= "Content-Transfer-Encoding: 7bit" . $email_eol;//Content-Transfer-Encoding
$email_headers .= "This is a MIME encoded message." . $email_eol;

// eamil message
$email_headers .= "--" . $time_separator . $email_eol;
$email_headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $email_eol;
$email_headers .= "Content-Transfer-Encoding: 8bit" . $email_eol;
$email_headers .= $body_message . $email_eol;

// attachment
$email_headers .= "--" . $time_separator . $email_eol;
$email_headers .= "Content-Type: application/octet-stream; name=\"" . $file_name . "\"" . $email_eol;
$email_headers .= "Content-Transfer-Encoding: base64" . $email_eol;
$email_headers .= "Content-Disposition: attachment" . $email_eol;
$email_headers .= $content . $email_eol;
$email_headers .= "--" . $time_separator . "--";
mail($mail_to, $email_subject, ", $email_headers); //SEND Mail TO USER

Leave a Comment

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

7  +  2  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US