HomePHP Page 6 - Building A PHP-Based Mail Client (part 3)
Under Construction - PHP
This third (and final) segment of our case study discusses theprocess of sending MIME-encoded email, demonstrating how to compose,forward and reply to email through a Web browser. It also discusses, indetail, the process of constructing a MIME-encoded message withattachments, explains PHP's HTTP upload capabilities, and examines thestandard error handler used throughout this case study.
In the event that attachments do exist, a couple of additional steps are required:
5. First, a unique boundary marker needs to be generated in order to separate the distinct parts of the message from each other. This boundary needs to be added to the message headers so that MIME-compliant mail clients know where to begin and end extraction of message parts.
<?
// if attachments exist
if($attachment_name || sizeof($amsg) > 0)
{
// create a MIME boundary string
// feel free to be original here!
$boundary = "=====MELONFIRE." . md5(uniqid(time())) . "=====";
// add MIME data to the message headers
$headers .= "MIME-Version:1.0\r\n";
$headers .= "Content-Type: multipart/mixed;
\r\n\tboundary=\"$boundary\"\r\n\r\n";
// start building a MIME message
}
?>
Note that the term "attachment" here refers to two types of
attachments: an uploaded attachment, or (only in the case of forwarded message), an attachment included from the original message. My message construction code must account for both types of attachments.
6. Next, a MIME message needs to be constructed, with the message body sent as the first section and the encoded attachments following it. Note the additional "--" that has to be appended to the specified boundary within the message itself - omit it and your MIME message will not be parsed correctly by a MIME-compliant mail client (you may remember this from the second part of this article).
<?
// if attachments exist
if($attachment_name || sizeof($amsg) > 0)
{
// create a MIME boundary string
// start building a MIME message
// first part is always the message body
// encode as 7-bit text
$str = "--" . $boundary . "\r\n";
$str .= "Content-Type: text/plain;\r\n\tcharset=\"us-ascii\"\r\n";
$str .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$str .= "$body\r\n\r\n";
// handle forwarded messages
}
?>
At this point, $str holds the message body.
7.
Assuming that this is a forwarded message which includes attachments, I'll need to first retrieve the selected attachment(s) from the original message. This involves connecting to the mail server, retrieving the message structure, parsing it with my custom parse() function, and pulling out the text-encoded attachment.
<?
// if attachments exist
if($attachment_name || sizeof($amsg) > 0)
{
// MIME message construction code
// if forwarded message, array $amsg[] will exist
// and contain list of attachments to be forwarded
if (sizeof($amsg) > 0)
{
// open message to be forwarded and parse it to find attachment
$inbox = @imap_open ("{". $SESSION_MAIL_HOST . "/pop3:110}",
$SESSION_USER_NAME, $SESSION_USER_PASS) or header("Location:
error.php?ec=3");
$structure = imap_fetchstructure($inbox, $id);
$sections = parse($structure);
// go through attachment list and message section
// if a match exists, create a MIME section and import that attachment
into the message
// do this as many times as there are attachments to be included
for ($x=0; $x<sizeof($amsg); $x++)
{
for ($y=0; $y<sizeof($sections); $y++)
{
if($amsg[$x] == $sections[$y]["pid"])
{
$data = imap_fetchbody($inbox, $id, $sections[$y]["pid"]);
$str .= "--" . $boundary . "\r\n";
$str .= "Content-Type: " . $sections[$y]["type"] . ";\r\n\tname=\"" .
$sections[$y]["name"] . "\"\r\n";
$str .= "Content-Transfer-Encoding: base64\r\n";
$str .= "Content-Disposition: attachment; \r\n\tfilename=\"" .
$sections[$y]["name"] . "\"\r\n\r\n";
$str .= $data . "\r\n";
}
}
}
}
// handle uploaded attachments
}
?>
Each included attachment is then added to the message string
($str) that is being constructed, with appropriate headers to describe the attachment type and name.
8. Next, we need some code to handle uploaded attachments (the second type). In this case, the uploaded file is in binary format and needs to be first encoded into BASE64 format before being attached to the message.
<?
// if attachments exist
if($attachment_name || sizeof($amsg) > 0)
{
// MIME message construction code
// handle forwarded messages
// if an uploaded attachment exists
// encode it and attach it as a MIME-encoded section
if ($attachment_name)
{
$fp = fopen($attachment, "rb");
$data = fread($fp, filesize($attachment));
$data = chunk_split(base64_encode($data));
fclose($fp);
// add the MIME data
$str .= "--" . $boundary . "\r\n";
$str .= "Content-Type: " . $attachment_type . ";\r\n\tname=\"" .
$attachment_name . "\"\r\n";
$str .= "Content-Transfer-Encoding: base64\r\n";
$str .= "Content-Disposition: attachment; \r\n\tfilename=\"" .
$attachment_name . "\"\r\n\r\n";
$str .= $data . "\r\n";
}
}
// all done
?>
The binary attachment is first converted into a text-based
BASE64 representation with PHP's base64_encode() function, and then added to the message string ($str). Note the chunk_split() function, used to split the BASE64-encoded text into data chunks suitable for insertion into an email message, and the HTTP upload variables created by PHP, used to add information to the Content-Type: and Content-Disposition: headers.
9. With all attachments handled, the final task is to end the MIME message with the boundary marker and an additional "--" at the end, signifying the end of the message.
<?
// all done
// add the final MIME boundary
$str .= "\r\n--$boundary--\r\n";
// assign the contents of $str to $body
// note that the original contents of $body will be lost
$body = $str;
?>
10. Finally, mail() the message out and display a status
message indicating whether or not the mail was accepted for delivery. Note that the Bcc: header is not correctly processed on Windows systems.
<?
// send out the message
if(mail($to, $subject, $body, $headers))
{
$status = "Your message was successfully sent.";
}
else
{
$status = "An error occurred while sending your message.";
}
?>
Whew! That was complicated, but I think the effort was worth
it. This script can now accept data entered into any of the three forms described previously, in addition to possessing the intelligence necessary to encode uploaded attachments or import forwarded ones. And it works like a charm - try it and see for yourself!