A MIME Mailer Class - You've Got Mail (
Page 2 of 4 )
The first order of business is to initialize some variables and provide a constructor for the class.
<?php
class mime_mailer
{
var $from;
var $to;
var $subject;
var $body = "";
var $headers;
var $files = array();
var $header_set = false;
var $body_set = false;
Some of these are pretty self explanatory. It's easy to see who the email is from, who it goes to, the subject and the body of the message. Other variables are provided for headers, an array is for file contents and two boolean values are intended as checks to determine that we have everything before sending the mail. It might be useful in some situations to employ email address validation before sending to help ensure that nothing goes wrong. Next is the constructor method.
function mime_mailer($to,$from,$subject,$body)
{
if($to != "" && $from != "" && $subject != "")
{
$this->to = $to;
$this->from = $from;
$this->subject = $subject;
if($body != "")
{
$this->body = $this->set_body($body);
}
$this->set_headers();
}
else
{
echo("Some constructor arguments are blank: mime_mailer");
exit();
}
}
As long as all the necessary values are valid, several variables are set with the constructor. In addition the "set_body()" method is called in order to place the body of the message inside the proper mime content. The "MIME_BOUNDRY" marks individual sections of the mail. Use two line returns before and after each content block (this goes for the attachment content as well).
function set_body($body)
{
$body_str = "--MIME_BOUNDRY\n";
$body_str .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$body_str .= "Content-Transfer-Encoding: quoted-printable\n";
$body_str .= "\n\n";
$body_str .= "$body";
$body_str .= "\n\n";
$this->body_set = true;
return $body_str;
}
The "set_headers()" method is also called to set some necessary mail headers. Values for email "from", "Reply-To" "X-Sender" and "Return-Path" are set from the "from" variable we set earlier.
function set_headers()
{
$this->headers = "From: ".$this->from." \r\n";
$this->headers .= "Reply-To: ".$this->from." \r\n";
$this->headers .= "MIME-Version: 1.0\r\n";
$this->headers .= "Content-Type: multipart/mixed;
boundary=\"MIME_BOUNDRY\"\n";
$this->headers .= "X-Sender: ".$this->from."\n";
$this->headers .= "X-Mailer: PHP4\n";
$this->headers .= "X-Priority: 3\n";
$this->headers .= "Return-Path: <".$this->from.">\n";
$this->headers .= "This is a multi-part message in MIME
format.\n";
$this->header_set = true;
}
Both of the above utility methods set a variable to true to indicate that the information has been set.