Send PHP mail with a file from server as attachment

by MD on 2009/09/25

Using this script below a mail using PHP can be sent with any file from server as attachment

<?PHP

$to = "xyz@dak.me";
// Address to wihch mail is to be sent

$subject = "Mail from http://dak.me with attachment";
// subject of mail

$bound_text = "Bound Text";
$bound = 	"--".$bound_text."\r\n";
$bound_last = 	"--".$bound_text."--\r\n";

$backup_filename = "somefile.zip";
// name of the file to be atttached.

$headers = 	"From: mukesh@dak.me\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;

$file = file_get_contents("http://xyz.com/temp/".$backup_filename);
// dont forget to specify actual location of attachment here

$message .="Content-Type: application/x-zip-compressed; name=$backup_filename\"\r\n"
  	."Content-Transfer-Encoding: base64\r\n"
  	."Content-disposition: attachment; file=$backup_filename\r\n"
  	."\r\n"
  	.chunk_split(base64_encode($file))
  	.$bound_last;

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

?>

You may also like:

Leave a Comment

Previous post:

Next post: