HomePHP Page 5 - Building A PHP-Based Mail Client (part 3)
Setting Boundaries - 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.
Now, if you've been paying attention, you'll have noticed one rather unusual thing about the three forms you've just seen. All of them point to the same form processor, "send.php". This might seem a somewhat odd choice on my part - after all, the three forms described above are all slightly different in character from each other, and you might think that writing a single processor for all three of them would be fairly complex - but bear with me and you'll see how it actually streamlines the entire mail delivery process.
You'll remember, from the second part of this article, how I had come up with a standard process flow to be followed while sending mail. The process involved first building the headers, then adding the message body and, if one or more attachments exist, encoding and appending them to the message body, with a unique boundary marker separating the various sections.
This is exactly what "send.php" is going to do. Take a look:
<?php
// send.php - send message
// includes and session check
// ensure that at least one field has values
if (!$to && !$cc && !$bcc)
{
header("Location: error.php?ec=6");
exit;
}
// check for valid file if attachment exists
if ($attachment_name && $attachment_size <= 0)
{
header("Location: error.php?ec=7");
exit;
}
// append signature to body
$sig = "\r\n--\r\nVisit http://www.melonfire.com/community/columns/trog/
for articles\r\nand tutorials on PHP, Python, Perl, MySQL, JSP and XML\r\n";
$body .= $sig;
// put all addresses into a single string
if($to) { $addresses .= $to . ","; }
if($cc) { $addresses .= $cc . ","; }
if($bcc) { $addresses .= $bcc . ","; }
// split address list into array
$all = split(",", $addresses);
// clean addresses
array_walk($all, "clean_address");
// validate each address further here
for($x=0; $x<sizeof($all); $x++)
{
if($all[$x] == "")
{
continue;
}
if(!validate_email($all[$x]))
{
header("Location: error.php?ec=8");
exit;
}
}
// build message headers
$headers = "From: $from\r\n";
if($cc) { $headers .= "Cc: $cc\r\n"; }
if($bcc) { $headers .= "Bcc: $bcc\r\n"; }
// if attachments exist
if($attachment_name || sizeof($amsg) > 0)
{
// create a MIME boundary string
$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
// 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";
// 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";
}
}
}
}
// 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
// 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;
}
// 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.";
}
?>
<html>
<head>
</head>
<body bgcolor="White">
<?
$title = "Send Message";
include("header.php");
?>
<font face="Verdana" size="-1">
<? echo $status; ?>
<p>
You can now <a href="list.php">return to the message list</a>, or <a
href="compose.php">compose another message</a>.
</font>
</body>
</html>
Yes, this is pretty complicated - but fear not, all will be
explained.
1. The first order of business is to perform certain basic checks on the data that is being submitted to "send.php". Consequently, in addition to the routine session check, I've added some code to ensure that the message has at least one recipient.
<?
// ensure that at least one field has values
if (!$to && !$cc && !$bcc)
{
header("Location: error.php?ec=6");
exit;
}
?>
2. If an attachment has been uploaded, it's also a good idea
to verify that the upload was successful. In order to perform these checks, I'm using the four variables created by PHP whenever a file is uploaded - $attachment holds the temporary file name assigned by PHP to the uploaded file, $attachment_size is the size of the uploaded file, $attachment _type holds the MIME type, and $attachment_name holds the original name of the file (you can read about this in detail at http://download.php.net/manual/en/features.file-upload.php)
<?
// check for valid file if attachment exists
if ($attachment_name && $attachment_size <= 0)
{
header("Location: error.php?ec=7");
exit;
}
?>
3. Next, I need to perform some basic validation on the
addresses entered into the form. I already have a function - do you remember validate_email()? - to perform this validation, but I need to first clean up the addresses entered into the form and reduce them to the user@host.name form.
The following code performs the address validation, redirecting the browser to the error handler if any of the addresses turn out to be invalid.
<?
// put all addresses into a single string
if($to) { $addresses .= $to . ","; }
if($cc) { $addresses .= $cc . ","; }
if($bcc) { $addresses .= $bcc . ","; }
// split address list into array
$all = split(",", $addresses);
// clean addresses
array_walk($all, "clean_address");
// validate each address further here
for($x=0; $x<sizeof($all); $x++)
{
if($all[$x] == "")
{
continue;
}
if(!validate_email($all[$x]))
{
header("Location: error.php?ec=8");
exit;
}
}
?>
In case you're wondering, the clean_address() function is a
tiny little function to reduce an email address to the user@host.name form, removing (among other things) whitespace, angle brackets and real names from the address text.
<?
// remove extraneous stuff from email addresses
// returns an email address stripped of everything but the address itself
function clean_address(&$val, $index)
{
// clean out whitespace
$val = trim($val);
// look for angle braces
$begin = strrpos($val, "<");
$end = strrpos($val, ">");
if ($begin !== false)
{
// return whatever is between the angle braces
$val = substr($val, ($begin+1), $end-$begin-1);
}
}
?>
4. The next step is to actually create headers reflecting the
recipient information.
Assuming that no attachments exist, this is a great place to
stop; all that's left to do is send the message using PHP's mail() function. But the attachment handling code is where all the meat really is - and it's explained on the next page.