I have written a function sendMail, which receives mail subject, message, senders email id and destination id. I also accept three optional parameters, namely cc, bcc and attachment file list. The function prepares appropriate mail headers and call mail function to send mail via SMTP server. The function returns true for mailing success and otherwise it will return false.
function sendMail( $subject, $message, $from, $to, $cc=null, $bcc=null, $attachment=null)
{
$headers = 'From: '.$from."\r\n";
if(!is_null($cc)){
$headers .= 'Cc: '.$cc ."\r\n";
}
if(!is_null($bcc)){
$headers .= 'Bcc: '.$bcc ."\r\n";
}
$headers .= 'MIME-Version: 1.0'."\r\n";
if(is_array($attachment) && count($attachment)>0){
$headers .= mailAttachmentHeader ($attachment, $message);
} else {
$headers .= 'Content-type: text/html; charset=iso-8859-1'."\r\n";
}
if(is_array($attachment) && count($attachment)>0){
$message = '';
}
$mailStatus = mail($to,$subject,$message,$headers);
echo "\nNew Mailer\n";
if($mailStatus){
return true;
}else{
return false;
}
}
Next we check is if attachments are present.
In case of no attachment we set 'Content-type: text/html; charset=iso-8859-1'."\r\n" – Rule 2.a. Otherwise we call the mailAttachmentHeader function to prepare the attachment header
function mailAttachmentHeader($attachment, $message )
{
$mime_boundary = md5(time());
$xMessage = "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"\r\n\r\n";
$xMessage .= "--".$mime_boundary."\r\n\r\n";
$xMessage .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$xMessage .= "Content-Transfer-Encoding: 7bit\r\n";
$xMessage .= $message."\r\n\r\n";
foreach($attachment as $file)
{
$xMessage .= "--".$mime_boundary."\r\n";
$xMessage .= "Content-Type: application/octet-stream; name=\"".basename($file)."\"\r\n";
$xMessage .= "Content-Transfer-Encoding: base64\r\n";
$xMessage .= "Content-Disposition: attachment; filename=\"".basename($file)."\"\r\n";
$content = file_get_contents($file);
$xMessage.= chunk_split(base64_encode($content));
$xMessage .= "\r\n\r\n";
}
$xMessage .= "--".$mime_boundary."--\r\n\r\n";
return $xMessage;
}
In mailAttachmentHeader function we set "Content-Type: multipart/mixed; bundary=\"".$mime_boundary."\"\r\n\r\n"; where value of $mime_boundary is the MD5 of current timestamp. – Rule 2.b.
To denote starting of message and each attachment following code is added
$xMessage .= "--".$mime_boundary."\r\n\r\n"; – Rule 3.b.
We add Content-type “text/html” for message and “application/octet-stream” for attachments – Rule 4
For each attachment we add "Content-Transfer-Encoding: base64\r\n"; – Rule 5 and "Content-Disposition: attachment; filename=\"".basename($file)."\"\r\n"; – Rule 6