Page 1 of 1

using mail() to send attachments

Posted: Fri Oct 28, 2005 2:00 pm
by titaniumdoughnut
Well, I've managed to get only so far on my own with this one. I am completely able to use mail() to send the results of a form to an email address, but what if I want to include a file that was uploaded to the form as an attachment?

I looked into a few online scripts that claim to do this (Mime Mail, PHPMailer) and the message simply never arrives. Surly it can't be that hard to write from scratch, right? But how do I start? I'm not in PHP 5 yet, if that matters.

Posted: Fri Oct 28, 2005 2:03 pm
by John Cartwright
search these forums for "mail attachment" and select Search for all terms

Posted: Fri Oct 28, 2005 2:06 pm
by Burrito
to do it from scratch, you'll need to know a lot about email headers.

I've done it and it's not super easy.

here is a snippet from a mail function that I wrote that will attach files:

Code: Select all

if($attachfrom != "")
	{
		$mime_boundary = "<<<:" . md5(uniqid(mt_rand(), 1));
		$headerz .= "MIME-Version: 1.0 \r\n";
		$headerz .= "Content-type: multipart/mixed; \r\n";
		$headerz .= " boundary=\"".$mime_boundary."\"\r\n";
		$content = "This is a multi-part message in MIME format. \r\n\r\n--".$mime_boundary."\r\n";
		
			if($htmlfrom != "" && $htmlfrom !== "no"){
		$content .= "Content-type: text/html;";
			}else{
		$content .= "Content-type: text/plain;";
			}
		$content .= " charset=\"iso-8859-1\"\r\n";
		$content .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
		$content .= $bodytextfrom."\r\n";
		$attachfiles = explode(",",$attachfrom);
		foreach($attachfiles as $smithjohnson){
		$data = chunk_split(base64_encode(file_get_contents($smithjohnson)));
		$content .= "--".$mime_boundary."\r\n";
		$content .= "Content-Disposition: attachment; \r\n";
		$filename = array_pop(explode("/",$smithjohnson));
		$content .= "Content-type: Application/Octet-Stream; name=\"".$filename."\"\r\n";
		$content .= "Content-Transfer-Encoding: base64 \r\n\r\n";
		$content .= $data."\r\n";
	}