#email, #php, #PHPMailer, #SMTP

Sending Email With PHPMailer

I’ve generally always handled forms with some quick and dirty php that used the standard mail() function to send me the resulting information. I never really got a good handle on setting that up properly, but, lucky for me, some one has done all of the dirty work by creating a class, PHPMailer, that was meant to handle emails quite a bit more extensively than I was able to do.

It’s actually fairly easy to get started using the class. This is the default implementation that the download provides for basic operation:

require_once('../class.phpmailer.php');

$mail             = new PHPMailer(); // defaults to using php "mail()"

$body             = file_get_contents('contents.html');
$body             = eregi_replace("[\]",'',$body);

$mail->AddReplyTo("name@yourdomain.com","First Last");
$mail->SetFrom('name@yourdomain.com', 'First Last');
$mail->AddReplyTo("name@yourdomain.com","First Last");

$address = "whoto@otherdomain.com";
$mail->AddAddress($address, "John Doe");

$mail->Subject    = "PHPMailer Test Subject via mail(), basic";

$mail->AltBody    = "This is for text based email"; // optional
$mail->MsgHTML($body);

$mail->AddAttachment("images/phpmailer.gif");      // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}

That is a very easy way to get up and running using the default mail() function. Most of the hard work has been done for you, all you’re left to do is to fill in the blanks. But hey, why go default when the thing provides you with some more advanced functionality? Like sending your email using SMTP.

The best way I found to handle my emails, and to send them using PHPMailer, was to create a component class, unoriginally named mmEmail, that would handle a few operations I needed in order to process the form and format the data.

class mmEmail {
        var $name          = null;
        var $email         = null;
        var $message       = null;
	var $time          = null;
	var $SMTP_host     = null;
	var $SMTP_username = null;
	var $SMTP_password = null;
	var $send_to       = null;
	var $send_name     = null;
        var $subject       = null;
	
	static $instance;
	
        public function __construct() {
		self::$instance = $this;
	}
        
        public function format($message) {
           //code that formats the message body
        }
        
        //this function handles the message template
        public function template($template) {
	    
		$name    = $this->name;
		$email   = $this->email;
		$message = $this->message;
		$time    = $this->time;
		
	        switch( $template ) {
		    case 'html' :
			    $the_body = $this->format($message);
	                    $body = 'html only';
				break;
				
			case 'text' :	
		            $body = 'text only';
				break;
				
			default :
			    break;
		
		}
		
		return stripslashes($body);
	}
   
        public function send() {
            //code to handle PHPMailer - I'll get to it.
        }
}

So this gets us set up to send our formatted email using the send() function above. That function uses PHPMailer to handle the heavy lifting.

function send() {
    $html_body  = $this->template('html'); //HTML Body
    $text_body  = $this->template('text'); //Text only body
		
    require("class.phpmailer.php");
    $mail   = new PHPMailer();
		
    $mail->IsSMTP(); //SMTP
    $mail->Host     = $this->SMTP_host;
    $mail->SMTPAuth = true;
    $mail->Username = $this->SMTP_username;
    $mail->Password = $this->SMTP_password;
        
    $mail->From     = $this->email;
    $mail->FromName = $this->name;
    $mail->AddReplyTo($this->email, $this->name);
    $mail->AddAddress($this->send_to, $this->send_name);
    $mail->Subject = $this->subject;
		
    $mail->IsHTML(true);
    $mail->Body    = $html_body;
    $mail->AltBody = $text_body;

    $result = $mail->Send();

    if($result)
    {
        echo 'Mail sent.';
    }
    else 
    {
        $result = $mail->ErrorInfo;
        return $result;
    }
}

Using my class is then fairly straight forward. I’ll define a few constants for my settings to make things easier for me to read, and from there sending an email is as simple as:

require("class.mmemail.php");
$email = new mmEmail();

$email->name          = NAME;
$email->email         = EMAIL;
$email->message       = MESSAGE;
$email->time          = TIME;
$email->SMTP_host     = SMTP_HOST;
$email->SMTP_username = SMTP_USERNAME;
$email->SMTP_password = SMTP_PASSWORD;
$email->send_to       = SEND_TO;
$email->send_name     = SEND_NAME;
$email->subject       = SUBJECT;
     
$email->send();

Why do something this complicated, when the result looks so much like the original PHPMailer setup? Because this allows me to format, check, and sanitize my data and then send my emails using a template system. I encourage you to take a look at a solution like this the next time you need a better way to send form emails.


PHPMailer can be found at: https://code.google.com/a/apache-extras.org/p/phpmailer/