using mail() to send attachments

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
titaniumdoughnut
Forum Commoner
Posts: 33
Joined: Wed Jul 13, 2005 2:02 pm
Location: Manhattan

using mail() to send attachments

Post 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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

search these forums for "mail attachment" and select Search for all terms
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post 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";
	}
Post Reply