Page 1 of 1

PHP Code for Email with Attachments

Posted: Fri May 26, 2006 11:01 am
by csmlola
How does one code emails with attachment? I once viewed a code for this but it got really confusing for me. Please help.

Posted: Fri May 26, 2006 5:45 pm
by feyd
find d11wtq's email class in Code Snippets.

Posted: Fri May 26, 2006 7:23 pm
by Chris Corbyn
To be brief, if you can't follow the code in that snippet it goes like this:

The email must be a multipart/mixed content type. This needs to define some sort of a boundary where one part starts and the next part begins.

The headers for the overall mail define this like so:

Code: Select all

Subject: Your subject
To: "Someone" <someone@address.com>
From: "You" <your@name.com>
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Type: multipart/mixed;
    boundary="some_randrom_string"
Now you need to patch together a sub-email for each part which you do like this:

Code: Select all

--some_random_string
Content-Type: text/html
Content-Transfer-Encoding: 7bit

<strong>This is a HTML email all rather annoyingly in bold!</strong>
You leave a blank line after the headers, which should immediately follow the MIME boundary you defined prepended with hypen, hypen " -- ".

Do this for all the parts you want.

Attachments are no different, they are just another part using that boundary, which are usually base64 encoded.
You do need to define the filename and specify the content-disposition to be an attachment though. To get the data for the attachment, just use:

Code: Select all

base64_encode(file_get_contents($filename));
So that would be another part looking like this:

Code: Select all

--some_random_string
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
Content-Dispostion: attachment;
    filename="Your filename.jpg"
Content-Description: Your filename.jpg

<base 64 encoded data here>
Stick all those parts together and end the email with the boundary prepended AND appended with hyphen, hyphen.

Code: Select all

Subject: Your subject
To: "Someone" <someone@address.com>
From: "You" <your@name.com>
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Type: multipart/mixed;
    boundary="some_randrom_string"

--some_random_string
Content-Type: text/html
Content-Transfer-Encoding: 7bit

<strong>This is a HTML email all rather annoyingly in bold!</strong>

--some_random_string
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
Content-Dispostion: attachment;
    filename="Your filename.jpg"
Content-Description: Your filename.jpg

<base 64 encoded data here>

--some_random_string--
That's it really :) You could of course just use an already developed mailer though ;)