I am wanting to send an email using PHP with an attachment, at the moment a simple text file will do.
So after reading the numerous previous posts on this subject I have come up with the following code:
<?PHP
// Configure file vars
$fileatt="mytext.txt";
$fileatt_type="text/plain";
$fileatt_name="mytext.txt";
// Start off the headers
$headers="From: a.user@domain.com";
// Open/Read/Close file
$file=fopen($fileatt,'rb');
$data=fread($file,filesize($fileatt));
fclose($file);
// Generate a boundary string
$semi_rand=md5(time());
$mime_boundary="==Multipart_Boundary_x{$semi_rand}x";
// Add the headers for a file attachment
$headers.="\nMIME-Version: 1.0\n"."Content-Type: multipart/mixed;\n"."boundary=\"{$mime_boundary}\"";
// Add a multipart boundary above the plain message
$message="This is the multi-part message in MIME format.\n\n"."--{$mime_boundary}\n"."Content-Type: text/plain; charset=\"iso-8859-1\"\n"."Content-Transfer-Encoding: 7bit\n\n"."Body of the email text"."\n\n";
// Base64 encode the file data
$data=chunk_split(base64_encode($data));
// Add file attachment to the message
$message .="--{mime_boundary}\n"."Content-Type: {$fileatt_type};\n"." name=\"{$fileatt_name}\"\n"." filename=\"{$fileatt_name}\"\n"."Content-Transfer-Encoding: base64\n\n".$data."\n\n"."--{$mime_boundary}--\n";
mail ("another_user@domain.com","test with attachment",$message,$headers);
echo "finished";
exit ();
?>
But I get:
From: a.user@domain.com
Date: Tue Mar 18, 2003 17:36:46 Europe/London
To: another_user@domain.com
Subject: test with attachment
Body of the email text
--{mime_boundary}
Content-Type: text/plain;
name="mytext.txt"
filename="mytext.txt"
Content-Transfer-Encoding: base64
c29tZSB0ZXh0IGluc2lkZSBhbiBhdHRhY2htZW50Cg==
Anyone know why this hasn't arrived as an attachment?
I am using MacOS X 10.2.4 with a mail client called Mail.
mytext.txt is in the same directory as this php script, and I do not think there are any issues such as permissions, it seems to be taking the file, as the larger the content of the file the longer the "coded" lettering I get.
I think my mail client doesn't understand the format, but maybe I've cocked up the code somewhere?
Andy.