Creating a simple mail sender class with PHP

In this tutorial I will show you how to create a simple mail sender class in PHP. Sending emails with PHP is a lot easier than you would think, however you need to care about some settings to avoid moving your emails into a spam folder.

Creating a simple mail sender class with PHP

In this tutorial I will show you how to create a simple mail sender class in PHP. Sending emails with PHP is a lot easier than you would think, however you need to care about some settings to avoid moving your emails into a spam folder.

Step 1.
To realize such a simple mailer class we will implement a function to create a mail header string with all important information like to, from, subject,...
Of course a function to send the mail and report error if necessary. Besides this we need some class variable to store the mail parameters.

The PHP built in mail function is quite simple, it is defined as:
bool mail ( string to, string subject, string message [, string additional_headers [, string additional_parameters]] )

The first 3 parameters -to, subject, message - are quite simple. However the additional_headers parameter is a little bit more complicated. This parameter string contains information like the from name, from email, replay address, MIME version, content type, character set and so on. Although this parameter is optional it is important as a lot of mail provider can delete your mails (because they think it is a spam or junk) if this parameters are not filled correctly.

Step 2.
After the theory lets begin with some coding. So let's create a new class and define all class variable for the above mentioned parameters and functions. The skeleton of the class looks like this:

<?php
class MicroMailer{
    var 
$to         = "";
    var 
$subject    = "";
    var 
$message    = "";
    var 
$fromName   = "";
    var 
$fromEmail  = "";
    var 
$replyEmail = "";
    var 
$header     = "";
    var 
$type       = "text/plain";
    var 
$characterSet = "iso-8859-1";
    
    
    function 
send(){
    }
    
    function 
createHeader(){
    }
    
}
?>


Explanation:
Almost all class variable are initialized with an empty string, except the type and character Set. This is because they can be the same all over the time, but in this way you can change it if you want to use other languages or want to send a html mail.

Step 3.
As we have all the parameters maybe you think we can send an email. It is almost right but before it we will create a well formatted mail header string. We will do it in the createHeader() function. It is not complicated at all but important. We just make some substitution in a predefined text. However we need to take care about the special characters after each parameters. The multiple extra headers should be separated with a CRLF (\r\n). So the function will returns with a well formatted header string. The code looks like this:

<?php
    
function createHeader(){
        
$from   = "From: $this->fromName <$this->fromEmail>\r\n";
        
$replay = "Reply-To: $this->replyEmail\r\n";    
        
$params = "MIME-Version: 1.0\r\n";
        
$params .= "Content-type: $this->type; charset=$this->characterSet\r\n";
        
        
$this->header = $from.$replay.$params;
        return 
$this->header;
    }
?>


Step 4.
Now our class is almost ready. The only thing is to really send the email. This step is quite easy, just get the header string using the above implemented createHeader() function and assign all parameters to the PHP mail() function. All we need to do is to check the return values to know whether the mail was sent correctly or not. The send() function looks like this:

<?php
    
function send(){
        
$this->createHeader();
        if (@
mail($this->to,$this->subject,$this->message,$this->header)){
            return 
true;
        } else {
            return 
false;
        }
    }
?>


Step 5.
As last step we create a html page to demonstrate how our new class works. We will create a simple form where the visitor can fill all the required fields and than these fields will be assigned to the corresponding mailer class fields.

So in this file first we need to import our new mailer class:

<?php require_once("microMailer.php"); ?>

And after we create the form and the form processing part.
The form looks like this:

      <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
        <table>
          <tr><td>To email:</td><td><input type="text" name="to" size="40" /></td></tr>
          <tr><td>From name:</td><td><input type="text" name="fromname" size="40" /></td></tr>
          <tr><td>From email:</td><td><input type="text" name="fromemail" size="40" /></td></tr>
          <tr><td>Reply email:</td><td><input type="text" name="replyemail" size="40" /></td></tr>
          <tr><td>Subject:</td><td><input type="text" name="subject" size="40" /></td></tr>
          <tr><td>Message:</td><td><textarea cols="30" rows="6" name="message"></textarea></td></tr>
          <tr><td colspan="2"><br/><input  type="submit" name="submitBtn" value="Send" /></td></tr>
        </table>
      </form>


And the processing part is this:

<?php
      $mailer 
= new MicroMailer();
        
      
$mailer->to         = isset($_POST['to']) ? $_POST['to'] : "";
      
$mailer->fromName   = isset($_POST['fromname']) ? $_POST['fromname'] : "";
      
$mailer->fromEmail  = isset($_POST['fromemail']) ? $_POST['fromemail'] : "";
      
$mailer->replyEmail = isset($_POST['replyemail']) ? $_POST['replyemail'] : "";
      
$mailer->subject    = isset($_POST['subject']) ? $_POST['subject'] : "";
      
$mailer->message    = isset($_POST['message']) ? $_POST['message'] : "";

      if (
$mailer->send()) {
        echo 
"Thanks for your message!";
      } else {
        echo 
"Sending email was failed!";
      }
?>


That's it.

Download:
You can download the complete code as well.