[KLUG Members] MIME attachments
Todd Pillars
todd at terralabs.com
Wed Nov 16 15:17:48 EST 2005
Robert G. Brown wrote:
> Fellow KLUGites and developers,
> I want to generate some email that will have one or more attachments, so I want to
> understand MIME very clearly.
>
> I don't want to build something based on a pile of libraries, as I'm trying
> to keep this thing reasonably portable and compact. I am thinking that we
> can build MIME'd messages for special cases rather easily....
>
> I've also looked for more detailed information about all this, but found very
> little. Perhaps it is swamped by all the references to various MIME-capable
> applications...
>
> I lok forward to your replies...
Her is a snippet I use to send both HTML and PDF files via email in PHP
but should be able to be adapted in any scripting language
if ($send_as_html == "html") {
$fileatt_type = "text/html";
} elseif ($send_as_html == "pdf") {
$fileatt_type = "application/pdf";
}
$fileatt = $pathtofile."/".$filename; // Path to the file
$fileatt_name = $filename; // Filename that will be used for the file
as the attachment
$email_from = $email_from."\r\n"; // Who the email is from
$email_subject = $email_subject."\r\n"; // The subject
$email_html = "<html>\n<head>\n</head>\n<body>\n";
$email_html .= "<p align=\"center\">";
$email_html .= "Email text"; // Message body of the email
$email_html .= "</body>\n</html>\n";
$email_to = $email_to; // Who the email is to
$file = fopen($fileatt,'r') or die("Could not open file");
$data = fread($file,filesize($fileatt)) or die ("Could not get file data");
fclose($file);
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;";
$headers .= " boundary=\"{$mime_boundary}\"\r\n";
$headers .= "From: ".$email_from."r\nReply-To: ".$reply_to."r\n";
$email_message .= "This is a multi-part message in MIME format.\n";
$email_message .= "--{$mime_boundary}\n";
$email_message .= "Content-Type:text/html; charset=\"iso-8859-1\"\n";
$email_message .= "Content-Transfer-Encoding: 7bit\n\n";
$email_message .= $email_html;
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n";
$email_message .= "Content-Type: {$fileatt_type};\n";
$email_message .= " name=\"{$fileatt_name}\"\n";
$email_message .= "Content-Transfer-Encoding: base64\r\n\r\n";
$email_message .= $data."\n\n--{$mime_boundary}--\r\n";
if (mail($email_to, $email_subject, $email_message, $headers)) {
echo "success";
} else {
echo "error";
}
Shortened a bit, but you should get the feel. Look for the boundries and
encoding.
Hope this helps
Todd
More information about the Members
mailing list