PHP

PHP Mail Class

Sunday, February 3rd, 2008

This is a very simple mailer class that is also easy to use.

<?php
/**
 * mail.php
 *
 * A (very) simple mailer class written in PHP.
 *
 * @author Zachary Fox
 * @version 1.0
 */

class ZFmail{
    var $to = null;
    var $from = null;
    var $subject = null;
    var $body = null;
    var $headers = null;

     function ZFmail($to,$from,$subject,$body){
        $this->to      = $to;
        $this->from    = $from;
        $this->subject = $subject;
        $this->body    = $body;
    }

    function send(){
      $this->addHeader(From: .$this->from."\r\n");
        $this->addHeader(Reply-To: .$this->from."\r\n");
        $this->addHeader(Return-Path: .$this->from."\r\n");
        $this->addHeader(X-mailer: ZFmail 1.0."\r\n");
        mail($this->to,$this->subject,$this->body,$this->headers);
    }

    function addHeader($header){
        $this->headers .= $header;
    }

}
?>

HTML code generated by vim-color-improved v.0.3.2.

Usage

Using the mail class is easy. Simply create a new ZFmail object, passing the parameters $to,$from,$subject, and $body, then call the method send on the object that you created. It’s as easy as pie. The following example is for a simple form mail script.

Example

<?php
/**
 * example/mail.php
 *
 * An example script to accept a post and send an email using ZFmail.
 *
 * @author Zachary Fox
 */

 // Include the mail.php file that holds the class definition
 require_once(mail.php);

 // First we set the to address. I would not let anyone put in a to 
 // address in a web form, and neither should you.
 $to =me@example.com‘;

 // Then we get the information we need from the $_POST array.
 // This step is not necessary, but in a production environment, 
 // we would process and sanitize this data here, rather than 
 // passing raw post data to the class.
 $from = $_POST['from'];
 $subject = $_POST['subject'];
 $body = $_POST['body'];

 // Then create the ZFmail object using the information from above
 $mail = new ZFmail($to,$from,$subject,$body);

 // Finally, call the object’s send method to deliver the mail.
 $mail->send();
?>

HTML code generated by vim-color-improved v.0.3.2.