PHP Send email with Attachment

PHP Send email with Attachment

The following code will allow you to send an email, with a file attachment without the need for a 3rd party library. This code assumes that you already have the upload and form fully operational.

	function XMail( $from, $fromname, $to, $subj, $text, $filename) { 
		//Open our file, rb = windows machine, you may need to change this to r for linux
		$f         = fopen($filename,"rb");
		//let's get a uniqueidentifier
		$un        = strtoupper(uniqid(time())); 
		//Set the from name and address
		$head      = "From: $fromname <$from>n"; 
		//set who we are sending this to
		$head     .= "To: $ton"; 
		//set the subject
		$head     .= "Subject: $subjn"; 
		//just for s's and giggles
		$head     .= "X-Mailer: PHPMail Tooln"; 
		//set the reply to address
		$head     .= "Reply-To: $fromn"; 
		//now we set our mime types, content types, and encoding
		$head     .= "Mime-Version: 1.0n"; 
		$head     .= "Content-Type:multipart/mixed;"; 
		$head     .= "boundary="----------".$un.""nn"; 
		$zag       = "------------".$un."nContent-Type:text/html;n"; 
		$zag      .= "Content-Transfer-Encoding: 8bitnn$textnn"; 
		$zag      .= "------------".$un."n"; 
		$zag      .= "Content-Type: application/octet-stream;"; 
		//pop in the filename for good measures
		$zag      .= "name="".basename($filename).""n"; 
		//now attach it
		$zag      .= "Content-Transfer-Encoding:base64n"; 
		$zag      .= "Content-Disposition:attachment;"; 
		$zag      .= "filename="".basename($filename).""nn"; 
		$zag      .= chunk_split(base64_encode(fread($f, filesize($filename))))."n";
		//this will return true or false if the send was successful
		return @mail("$to", "$subj", $zag, $head);
	}
Kevin Pirnie
22 Years of PC and server maintenance & over 17 years of web development/design experience; you can rest assured that I take every measure possible to ensure your computers are running to their peak potentials. I treat them as if they were mine, and I am quite a stickler about keeping my machines up to date and optimized to run as well as they can.