PHP Mail - Send HTML email with attachment

As the title says, we are going to discuss how to send mail with attachment using the default PHP mail() function.
Sending a plain text / HTML email using PHP mail is very simple but when it comes to adding attachments to it then it becomes equally tricky and difficult.
I was caught up in this tricky situation and after searching around and trying zillions of solutions suggested by users in various forums got the following solution to work;
Hope this comes handy to someone in need :-)

This is the code that worked for me;

/* Email Detials */
  $mail_to = $to;
  $from_mail = $from;
  $from_name = $from_name;
  $reply_to = $from;
  $subject = $subject;
  $message_body = $msg;

/* Attachment File */
  // Attachment location
  $file_name = $basefilename;
  $path = "../reports/";
 
    // Read the file content
    $file = $path.$file_name;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
   
/* Set the email header */
    // Generate a boundary
    $boundary = md5(uniqid(time()));
   
    // Email header
    $header = "From: ".$from_name." \r\n";
    $header .= "Reply-To: ".$reply_to."\r\n";
    $header .= "cc: ".$cc."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
   
    // Multipart wraps the Email Content and Attachment
    $header .= "Content-Type: multipart/mixed;\r\n";
    $header .= " boundary=\"".$boundary."\"";

    $message .= "This is a multi-part message in MIME format.\r\n\r\n";
    $message .= "--".$boundary."\r\n";
   
    // Email content
    // Content-type can be text/plain or text/html
    $message .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n";
    $message .= "Content-Transfer-Encoding: 7bit\r\n";
    $message .= "\r\n";
    $message .= "$message_body\r\n";
    $message .= "--".$boundary."\r\n";
   
    // Attachment
    // Edit content type for different file extensions
    $message .= "Content-Type: application/csv;\r\n";
    $message .= " name=\"".$file_name."\"\r\n";
    $message .= "Content-Transfer-Encoding: base64\r\n";
    $message .= "Content-Disposition: attachment;\r\n";
    $message .= " filename=\"".$file_name."\"\r\n";
    $message .= "\r\n".$content."\r\n";
    $message .= "--".$boundary."--\r\n";
   
    // Send email
    if (mail($mail_to, $subject, $message, $header)) {
        echo "Sent";
    } else {
        echo "Error";
    }


Credit goes to user Karmaprod at the forum eureka.ykyuen.info
link: http://eureka.ykyuen.info/2010/02/16/php-send-attachmemt-with-php-mail/

0 comments:

Post a Comment