Saturday, April 2, 2011

Mail Attachment with PHP

Mail attachments are tricky with php are tricky. After hours of research, and allot of trial and error I finally learned how to do mail attachments.

Example:



$to =     'ilive72@hotmail.com';
$subject =     'PHP Mail Attachment Test';
$bound_text =     "jimmyP123";
$bound =     "--".$bound_text."\r\n";
$bound_last =     "--".$bound_text."--\r\n";
     
$headers =     "From: admin@server.com\r\n";
$headers .=     "MIME-Version: 1.0\r\n"
      ."Content-Type: multipart/mixed; boundary=\"$bound_text\"";
     
$message .=     "If you can see this MIME than your client doesn't accept MIME types!\r\n"
      .$bound;
     
$message .=     "Content-Type: text/html; charset=\"iso-8859-1\"\r\n"
      ."Content-Transfer-Encoding: 7bit\r\n\r\n"
      ."hey my good friend here is a picture of regal beagle\r\n"
      .$bound;
     
$fileatt = "./008.jpg";
$file = fopen($fileatt,'rb');
$data = fread($file, filesize($fileatt));
   
//$file =     file_get_contents("http://internetinfoanddesign.com/webdevelopment/brockconnect/admin/008.jpg");

//When adding the attachment, you must include a slash n escape
     
$message .=     "Content-Type: image/jpg; name=\"008.jpg\"\n"
      ."Content-Transfer-Encoding: base64\n"
      ."Content-disposition: attachment\n; file=\"008.jpg\"\n"
      ."\n\n"
      .chunk_split(base64_encode($data))
    //.chunk_split(base64_encode($file))
      .$bound_last;

if(mail($to, $subject, $message, $headers))
{
     echo 'MAIL SENT';
} else {
     echo 'MAIL FAILED';
}

?>

No comments:

Post a Comment

Programming for the Web