I came up with some code today.  I started e-mailing myself file
attachments to see what my e-mail program did in preparing them and when
I opened the e-mails I changed the view to "show e-mail source".  

The biggest challenge is the boundary that separates the e-mail message
text from the file attachment.  I found this command on php.net here to
generate the boundary:

$boundary = md5(uniqid(time()));

Then it is like baking cookies --- You just fill in the pieces:

You have to include

$headers .= "Content-Type: multipart/mixed; boundary=\"". $boundary .

in the header field of the mail() function.  (It is important the
boundary has "'s around it)

Then you have to have these lines before the text of the message (I
have /html for creating an HTML based e-mail):

$message = "--" . $boundary . "
Content-Type: text/html; charset=ISO-8859-1
Content-Transfer-Encoding: 7bit
{blank line}
E-mail message text is here


and then for the file attachment headers you put in these lines:

$file_attachment_header = "--" . $boundary;
$file_attachment_header .= "Content-Disposition: attachment;
$file_attachment_header .= "Content-Type: application/pdf;
$file_attachment_header .= "Content-Transfer-Encoding: base64\r\n";

and then you convert your file over to 64 bit encoding

$data = file_get_contents($file);
chunk_split( base64_encode($data), 68, "\n");

#you want to limit each line to a certain number of characters, 
#in this example 68 so it will go through the mail server ok

Now close off the e-mail with this final boundary
$footer = "--" . $boudary . "--";

$message = $message . $file_attachment_header . $data . $footer;

#file attachments and the file attachment headers are 
#really part of the e-mail message

Then you issue the command

mail($email_address, $email_subject, $message, $headers);


On Thu, 2006-05-11 at 18:33 -0400, Ron Piggott (PHP) wrote:
> Does any one know how to send a file attachment using PHP?  
> I have been using the mail() command to send e-mail in various scripts,
> but have spotted a file attachment syntax to use on the php web page.
> Ron

PHP Database Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to