FREE THOUGHT · FREE SOFTWARE · FREE WORLD

PHPMailer tutorial

This is meant to be an improved version of the article written by PHPFreaks founder, Eric Rosebrock on the PHPFreaks site HERE, simply because I noticed the URL for that tutorial often was down, so I rewrote it (close to verbatim) for my own personal use.


PHPMailer is by far the BEST way to add email functionality to your web site.

This is just an article to point you in the right direction to mastering this incredible php package.

Tutorials, Guides, Documentation, and HowTos

Other PHPMailer links

Introduction

Sending E-Mail through PHP can be simple, or it can be very complex depending on what you want to do. A standard plain-text E-Mail is what most developers resort to because building the MIME headers for HTML mail can be a difficult process. Those days have been over for quite some time with the amazing PHPMailer library that is available for free! In this tutorial, I will discuss in detail the features and possibilities you have when dealing with PHPMailer.

Requirements

The requirements of this tutorial are very limited. You only need PHP and the ability to send mail() function or an SMTP connection. You should also have a basic understanding of dealing with Object Oriented Programming (OOP) or at least how to follow the examples we'll use in this tutorial.

Don't sweat it, this is going to be an easy tutorial for you to follow!

About PHPMailer

PHPMailer is a fully featured email transfer class for PHP that I would put above all of the other E-Mail handlers that I've used. It's popularity has grown rapidly over the past years that is has been around. Announced on the PHPMailer website on December 7, 2004, it has reached over 100,000 downloads! I hope you will want to increment that counter by reading this tutorial, and more importantly, learn how to enable E-Mail features you have only dreamed of!

PHPMailer Features

At the time this tutorial was written, here is a list of features currently available:

  • Can send emails with multiple TOs, CCs, BCCs and REPLY-TOs
  • Redundant SMTP servers
  • Multipart/alternative emails for mail clients that do not read HTML email
  • Support for 8bit, base64, binary, and quoted-printable encoding
  • Uses the same methods as the very popular AspEmail active server (COM) component
  • SMTP authentication
  • Word wrap
  • Address reset functions
  • HTML email
  • Tested on multiple SMTP servers: Sendmail, qmail, Postfix, Imail, Exchange, Mercury, Courier
  • Works on any win32 or *nix platform
  • Flexible debugging
  • Custom mail headers
  • Multiple fs, string, and binary attachments (those from database, string, etc)
  • Embedded image support

PHPMailer Contributors

The following contributors to PHPMailer are:

  • Brent R. Matzelle
  • Patrice Fournier
  • Chris Ryan
  • Cem Hurturk
  • Tom Klingenberg
  • Jaime Bozza

I give these folks great respect for what they have done to speed up my development time on various projects in the past, including PHPFreaks.com!

Preparing PHPMailer for Use

Let's download, unpack and prepare PHPMailer!

Downloading and Unpacking

The first thing you have to do is of course, download PHPMailer! You can get it at: http://phpmailer.sourceforge.net/ . Once you have the files downloaded, simply extract them into a directory. In this tutorial, we'll assume that your website is setup for this directory structure: /web/mywebsite/public_html/. Now, what you want to do is create a couple of directories for structuring your web area. I usually put libraries under 'lib' and then their name. So, we'll extract PHPMailer into /web/mywebsite/public_html/lib/phpmailer and the contents of this directory looks like this with the files in place:

/web/mywebsite/public_html/lib
/web/mywebsite/public_html/lib/phpmailer
/web/mywebsite/public_html/lib/phpmailer/docs
/web/mywebsite/public_html/lib/phpmailer/docs/extending.html
/web/mywebsite/public_html/lib/phpmailer/docs/faq.html
/web/mywebsite/public_html/lib/phpmailer/docs/timeoutfix.diff
/web/mywebsite/public_html/lib/phpmailer/language
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-br.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-cz.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-de.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-en.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-es.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-fr.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-it.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-nl.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-no.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-se.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-tr.php
/web/mywebsite/public_html/lib/phpmailer/phpdoc
/web/mywebsite/public_html/lib/phpmailer/phpdoc/allclasses-frame.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/deprecated-list.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/help-doc.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/index-all.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/index.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/overview-tree.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/packages.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/phpmailer.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/serialized-form.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/stylesheet.css
/web/mywebsite/public_html/lib/phpmailer/test
/web/mywebsite/public_html/lib/phpmailer/test/phpmailer_test.php
/web/mywebsite/public_html/lib/phpmailer/test/phpunit.php
/web/mywebsite/public_html/lib/phpmailer/test/rocks.png
/web/mywebsite/public_html/lib/phpmailer/ChangeLog.txt
/web/mywebsite/public_html/lib/phpmailer/class.phpmailer.php
/web/mywebsite/public_html/lib/phpmailer/class.smtp.php
/web/mywebsite/public_html/lib/phpmailer/LICENSE
/web/mywebsite/public_html/lib/phpmailer/README

Now that we have those files in place, let's move on to creating our site configuration file!


Creating and Using a Site Configuration File

One of the things I like to do when I build a site is to create a configuration file that handles miscellaneous settings that I may need over and over again. So, I create a file called config.php in /web/mywebsite/public_html/config.php and I set it up with an array called $site with my keys and values the settings I use in the site. In this tutorial, I will cover how to define some settings we will use for the PHPMailer extender class. Here's a view of my configuration file: config.php


The previous example should be very self explanatory, so we'll move on and cover those settings later on when we start to use them.

The PHPMailer Extender Class

First, I want to emphasize, you do not need to create an extender class, but to make life easier for us, I'm going to show you how to anyways.

The extender class will basically call the PHPMailer() class and then setup the basic values for you such as the Email address you want to send from, mail server settings and etc. Each of these settings are inherited by the config.php by default, but you may also overwrite them when you call our extender class. For example, if you do not define the settings in the extender class, they will be set by default and this in turn, allows you to setup the basic values without actually going through the motions every time. That's the beauty of it!

Here's a look at our extender class:

MailClass.inc

Host = $site['smtp_host'];
            $this->Port = $site['smtp_port'];
            if($site['smtp_username'] != '')
            {
                $this->SMTPAuth = true;
                $this->Username = $site['smtp_username'];
                $this->Password = $site['smtp_password'];
            }
            $this->Mailer = "smtp";
        }
        if(!$this->From)
        {
            $this->From = $site['from_email'];
        }
        if(!$this->FromName)
        {
            $this-> FromName = $site['from_name'];
        }
        if(!$this->Sender)
        {
            $this->Sender = $site['from_email'];
        }
        $this->Priority = $this->priority;
    }
}
?>

The PHP Mail Class

FreakMailer Class Code Breakdown

The FreakMailer class previously displayed is pretty simple. You only need a very basic understanding of Object Oriented Programming to use it, so let's break it down now.

First, we are going to call the class.phpmailer.php file from within our phpmailer lib directory under the document root. This allows us to extend the PHPMailer class because it makes that object available. You could include this elsewhere, but this is a good place to do so.

require_once($_SERVER['DOCUMENT_ROOT'].'/lib/phpmailer/class.phpmailer.php');

Class Control Structure

Next, we define the class control structure and give our new class a name while extending the PHPMailer class.

class FreakMailer extends PHPMailer
{

Class Variables

Moving along, we now setup the internal variables. Most of these are set to null by default so that we can do some triggering later on to determine if you want to overwrite the default values from the config.php file.

var $priority = 3;
var $to_name;
var $to_email;
var $From = null;
var $FromName = null;
var $Sender = null;

Let's take a look at these values now:

  • $priority - This sets the mail priority by default. Values: 1 = High, 3 = Normal, 5 = Low
  • $to_name - This is the name of the person you are sending to
  • $to_email - The E-Mail address of the person you are sending to
  • $From - The E-Mail address you want to send from
  • $FromName - The Name of the sender.

Now that we have those variables defined, we can discuss the FreakMailer() function

FreakMailer() Function

This is the function that basically sets up the default values for the PHPMailer to send E-Mail with. In other words, it's the whole reason we are using this class.

First, we call the $site array from our config.php so that it can be used within this function and class. There are a couple of ways we can do this, we could point to it from outside of the class, or we can just global it. Using the global call is the easiest method and it works, so let's just do that!

function FreakMailer()
{
    global $site; // Comes from config.php $site array

Next, we start the bulk of the operations here and start passing in values to the PHPMailer class. There's not much to explain here, if the internal value ($this->setting) of the setting is not defined after you instantiate the class, it basically calls it from the config.php and we'll use that instead. I mentioned earlier that you can override the values in the config.php and this is where those checks come into play.

    if($site['smtp_mode'] == 'enabled')
    {
        $this->Host = $site['smtp_host'];
        $this->Port = $site['smtp_port'];
        if($site['smtp_username'])
        {
            $this->SMTPAuth = true;
            $this->Username = $site['smtp_username'];
            $this->Password = $site['smtp_password'];
        }
        $this->Mailer  = "smtp";
    }

    if(!$this->From)
    {
        $this->From = $site['from_email'];
    }
    if(!$this->FromName)
    {
        $this->FromName = $site['from_name'];
    }
    if(!$this->Sender)
    {
        $this->Sender = $site['from_email'];
    }
    $this->Priority = $this->priority;
}

The most important thing you need to understand is that all of the functionality in the PHPMailer is still present and can be used even though we've extended the class. The only thing we've done here is created an extension (hence extends) that takes care of the repetitive stuff we don't want to do every time we need to send an E-Mail

Now that we have a good understanding of the extender class, let's move along and start sending some E-Mail!

Sending E-Mail with PHP

Sending E-Mail with PHPMailer

We've done our work and we've got everything ready to go to start sending E-Mail with PHPMailer. Let's give it a go and see how everything works!

Basic Test

This test is very important to this tutorial because we will be referring to this basic test code throughout the tutorial when I show you how to use different features with PHPMailer. If this test does not work for you, read through the tutorial again and keep trying until it does work, othewise you will be lost later on!

Our first code example is going to be a file looks like this:

Subject = 'This is a test';

// Body
$mailer->Body = 'This is a test of my mail system!';

// Add an address to send to.
$mailer->AddAddress('foo@host.com', 'Eric Rosebrock');

if(!$mailer->Send())
{
    echo 'There was a problem sending this mail!';
}
else
{
    echo 'Mail sent!';
}
$mailer->ClearAddresses();
$mailer->ClearAttachments();
?>

Let's break down this file so that we have a good understanding of what it does.

First, we are going to include our config.php file within the Document Root so that we have the $site settings available.

// Grab our config settings
require_once($_SERVER['DOCUMENT_ROOT'].'/config.php');

You could do this next step within the config.php file, but to make things easier, I chose not to.

// Grab the FreakMailer class
require_once($_SERVER['DOCUMENT_ROOT'].'/lib/MailClass.inc');

Next, we are going to call up our FreakMailer class and when we do this, we'll also initialize the PHPMailer class as well by the extends definition in the FreakMailer class.

// instantiate the class
$mailer = new FreakMailer();

Ok, so now we have PHPMailer ready to go with all of our default settings, let's go ahead and define a subject:

// Set the subject
$mailer->Subject = 'This is a test';

Now let's define the body of the message:

// Body
$mailer->Body = 'This is a test of my mail system!';

NOTE:
If you are using plain text E-Mail, which is the default, you need to convert new lines by using n or rn and you should use double quotes in the strings such as $mailer->Body. Otherwise for single quotes you can start your string and type it out however you want it in your PHP script and press for each new line you wish to make and when you are done with your string, just end it with the semicolon like normal.

Now, add an address to send to. The AddAddress accepts two inputs. The first is the E-mail address to send to and the second is the Name of the person you are sending to.

// Add an address to send to.
$mailer->AddAddress('foo@host.com', 'Eric Rosebrock');

Next, we send the message and look for an error:

if(!$mailer->Send())
{
    echo 'There was a problem sending this mail!';
}
else
{
    echo 'Mail sent!';
}

Obviously, if an error is detected, you will see There was a problem sending this mail!, otherwise you will see: Mail sent!

Finally, we will clear the attatchment list and the Address list. This is primarily for sending Mailing lists, but I do it anyways as a (bad?) habit.

$mailer->ClearAddresses();
$mailer->ClearAttachments();
?>

If you have just sent yourself an E-Mail with PHPMailer, then congratulations, you're on your way to sending E-Mail with PHP the easy way!

Common Problems

Here's a list of some common problems you may have with sending E-Mail through PHPMailer (these problems would probably be the same with the standard mail() function as well.).

  • No SMTP server Running on the local machine - You need some type of SMTP server running!
  • Improper setup of the PHP script - Please review through the tutorial again until it works.
  • The Apache Web Server is not allowed to relay through the SMTP server on the local machine (typical with some web hosts).
  • You did not define the recipient properly.

Alright! If you haven't had any problems, let's move along to sending E-Mail with additional features. Let's move on to using some additional features in PHPMailer!


Email with PHP - BCC, CC, Reply-TO, Multiple Recipients


Using PHPMailer's Additional Features

If you're at this point and you have not read the entire tutorial yet, please go back and read. We will be extending on the Basic Example from this point forward.

PHPMailer has many features such as adding attachments, the ability to send a mailing list, multiple recipients, and much more. In this section of the tutorial, we're going to show you how to do most of those.

Handling E-Mail Addresses

PHPMailer supports many E-Mail address features, such as TO and FROM, multiple recipients, Carbon Copy (BCC), Reply-To addresses and more. Let's review how to utilize these features.

Remember, we are building upon the Basic Example presented earlier in this tutorial, however you can generally apply these methods into any PHPMailer usage because these functions are in the main class.

Adding the FROM Address

In our file and our extender class, however you can override that at any time. Here's an example:

$mailer->FromName = 'Your Name';
$mailer->From = 'You@yourdomain.com';

That was pretty simple! If you do not define the FromName by default in the class, it will show up as the E-Mail address in most clients.

Adding a Reply-To Address

By default the Reply-To address will be the FROM address unless you specify otherwise. That is simply E-Mail client intelligence. However, you can have the E-Mail come from one E-Mail address and any replies go to a different one. Here's how:

$mailer->AddReplyTo('billing@yourdomain.com', 'Billing Department');

NOTE:
You can have multiple Reply-To addresses, just duplicate the line in the previous code example and change the E-Mail address on each line.

Adding Multiple Recipients

This method allows you to add multiple recipients to a single E-Mail address. I would not recommend this for anonymous mailing lists, or sending mailing lists. See later in this tutorial for a mailing list example.

To add multiple Recipients, all you have to do is call the AddAddress function once for each E-Mail address you want to send to. Here's an example of three E-Mail addresses:

NOTE:
There are two arguments in this function. (Recipient Email Address, Recipient Name). The Recipient Name is optional and will not be used if not present.

$mailer->AddAddress('recipient1@domain.com', 'First Person');
$mailer->AddAddress('recipient2@domain.com', 'Second Person');
$mailer->AddAddress('recipient3@domain.com', 'Third Person');

NOTE:
It is not recommended to use this method to send out mailing lists! Every recipient that gets the mail will see everyone else's E-Mail address and you may have just violated any kind of trust for your mailing list users! See later in this tutorial for sending Mailing lists.

Adding Carbon Copy CC Recipients

To carbon copy (CC) recipients you can add them to the E-Mail going out by using the following methods. Just like the Adding Multiple Recipients example, you can add multiple CC recipients as well.

$mailer->AddCC('recipient1@domain.com', 'First Person');

// More than one CC, just keep adding them!
$mailer->AddCC('recipient2@domain.com', 'Second Person');
$mailer->AddCC('recipient3@domain.com', 'Third Person');

Adding Blind Carbon Copy BCC Recipients

The "invisible" recipients or BCC can be added to an E-Mail going out by using the following methods. Just like the Adding Multiple Recipients example, you can add multiple BCC recipients as well.

$mailer->AddBCC('recipient1@domain.com', 'First Person');

// More than one BCC, just keep adding them!
$mailer->AddBCC('recipient2@domain.com', 'Second Person');
$mailer->AddBCC('recipient3@domain.com', 'Third Person');

Adding a Reply-To Address

By default the Reply-To address will be the FROM address unless you specify otherwise. That is simply E-Mail client intelligence. However, you can have the E-Mail come from one E-Mail address and any replies go to a different one. Here's how:

$mailer->AddReplyTo('billing@yourdomain.com', 'Billing Department');

NOTE:
You can have multiple Reply-To addresses, just duplicate the line in the previous code example and change the E-Mail address on each line.

Adding Multiple Recipients

This method allows you to add multiple recipients to a single E-Mail address. I would not recommend this for anonymous mailing lists, or sending mailing lists. See later in this tutorial for a mailing list example.

To add multiple Recipients, all you have to do is call the AddAddress function once for each E-Mail address you want to send to. Here's an example of three E-Mail addresses:

NOTE:
There are two arguments in this function. (Recipient Email Address, Recipient Name). The Recipient Name is optional and will not be used if not present.

$mailer->AddAddress('recipient1@domain.com', 'First Person');
$mailer->AddAddress('recipient2@domain.com', 'Second Person');
$mailer->AddAddress('recipient3@domain.com', 'Third Person');

NOTE:
It is not recommended to use this method to send out mailing lists! Every recipient that gets the mail will see everyone else's E-Mail address and you may have just violated any kind of trust for your mailing list users! See later in this tutorial for sending Mailing lists.

Requesting a Read Receipt

If you want to request a Read Receipt from the person who receives the E-Mail, you can use the following setting:

$mailer->ConfirmReadingTo = 'you@youdomain.com';

Now that we've covered E-Mail addresses, let's move along to sending the beloved HTML Mail!


HTML Mail with PHP


Sending HTML Mail with PHP and PHPMailer

HTML Mail has proven to be one of the more complicated tasks when sending E-Mail through PHP. Setting the MIME types and building the boundaries of an HTML body are not easy to do and it takes some considerable research to get it right. However, PHPMailer has made life easy for us and I will show you how to do this now.

Important Notes on HTML Mail

Before we go to far into sending HTML mail, I want you to understand that it is important to know how images and files such as CSS and etc should be handled. A simple rule is to store them on the web server and file on the web server in your HTML that will be compiled and sent through the HTML Mail. If you go crazy and add a bunch of files to an E-Mail and try to call them within the E-Mail itself, you're in for one huge headache. An example of my HTML body would be something like:



My HTML Email



PHP Freaks Rules!

We invite you to visit PHP Freaks.com for a loving community of PHP Developers who enjoy helping each other learn the language!

Sincerely,
PHP Freaks Staff

In the previous example, I made every link a full URL and not a shortcut relative to my document root. If you do not do this, then your images and URLs will be broken!

Moving along, now we are going to send the HTML mail by setting the body and a the isHTML setting in PHPMailer. Once again, this example expands upon the Basic Example earlier in this tutorial.

$htmlBody = '

My HTML Email



PHP Freaks Rules!

We invite you to visit PHP Freaks.com for a loving community of PHP Developers who enjoy helping each other learn the language!

Sincerely,
PHP Freaks Staff

'; $mailer->Body($htmlBody); $mailer->isHTML(true); // Send the E-Mail
Alternate Text Bodies For HTML Mail

You should never rely on HTML only E-Mails if your message is important. Instead, you should do your recipient a favor and send a text-only version of the E-Mail along with the HTML body in case their E-Mail client cannot display the HTML version.

We can accomplish this by defining the AltBody setting of the PHPMailer class. This setting will be the plain text version of your E-Mail and if it is set or Not Empty, the ContentType of the E-Mail is automatically set to multipart/alternative. Here's how you would do this:

// setup the $mailer class

$htmlBody = 'My HTML Body....';
$textBody = 'My text-only body....';

$mailer->Body($htmlBody);
$mailer->isHTML(true);
$mailer->AltBody($textBody);

// Send the mail...

Now two formats of E-Mail will be sent to the recipient.

Let's move along to File Attachments with PHPMailer


PHP File Attachements



File Attachments in PHP Mail with PHPMailer

Sending file attachments is really easy to do. You simply add them to the attachment just like you would an address, cc, bcc or reply-to, except using the proper function. See the example below:

// Setup mail class, recipients and body
$mailer->AddAttachment('/web/mywebsite/public_html/file.zip', 'file.zip');

The AddAttachment function has four arguments:

AddAttachment(PATH_TO_FILE, FILENAME, ENCODING, HEADER_TYPE)

The PATH_TO_FILE is naturally the full path of the header you want to send. Application/octet-stream is default.

That was pretty easy! Let's move along to using SMTP servers and utilizing diferent types of local E-mail SMTP servers.


SMTP Servers with PHP Mail


Using External SMTP Server(s) with PHP Mail

First, let's discuss using external SMTP servers instead of localhost. In this tutorial, we setup a config.php file. Inside this file, we have a few options for SMTP servers. If you want to simply enable one more more SMTP servers, you can do so through this configuration file by setting $site['smtp_enabled'] = 'enabled';

In the $site['smtp_host'] setting you can have a list of SMTP servers to send through delimited by a semicolon:

From my understanding of this SMTP setting, PHPMailer will send E-Mail through the main host first and if it cannot connect, it will go to the next one in the list.

NOTE:
Remember, you can enable SMTP authentication and change the SMTP port via your config.php file with the basic settings that we created.

One important thing to note about sending through SMTP is that instead of using the standard Send() function, you will use SMTPSend(); Example:

// Class and mail body setup here....
// See basic Example.

// Non SMTP Mode:
// $mailer->Send();

// SMTP Mode:
$mailer->SmtpSend();

SMTP Mail Problems

There are many things that can go wrong with sending mail through SMTP and most of the problems come from permission issues.

  • Does your Host have permission to relay through the SMTP Host?
  • Does your host require POP before SMTP?
  • Does your Host require SMTP authentication?
  • Are your SMTP settings correct for the remote host username / password?

NOTE:
Unfortunately, I do not believe PHPMailer supports POP before SMTP. If this is a problem for you, you should contact your system administrator and request a RELAY HOST be setup for your webserver's IP address.

Taking Advantage of qmail and Sendmail with PHP Mail

If you want to bypass the PHP Mail server and then PHPMailer will execute that Binary which could possibly speed things up quite a bit.

qmail Example:

// Setup Mail class and features
$mailer->IsQmail();
$mailer->Send();

Sendmail Example:

// Setup Mail class and features
$mailer->IsSendmail();
$mailer->Send();

That was pretty easy! Let's move along to creating a simple Mailing list with PHPMailer!


PHP Mailing List Example


PHP Mailing List Example

Now that you have a good understanding of the PHPMailer and how it works, let's discuss some Mailing List features. A few considerations you may have about sending mailing lists are customizable subjects, bodies and possibly even content. More importantly, is the ability to hide the E-Mail addresses of everyone else on the list from each other.

This example assumes that you already have some sort of database setup for mailing list users and you know how to connect to MySQL and query data. If you don't know how to do that, then there's some tutorials on this site that can help you get to this point. For now, we'll assume that we have something of the following table structure:

  • FirstName
  • LastName
  • EmailAddress
  • MailType (text / html)

Let's assume that you have 50 users in your database and you want to E-Mail them all a customizable E-Mail. The following code will accomplish this for you:


Check out PHP Freaks: http://www.phpfreaks.com

Sincerely,
Admin"; // instantiate the class $mailer = new FreakMailer(); // Get the user's Email $sql = mysql_query("SELECT FirstName,LastName,EmailAddress,MailType FROM users WHERE 1"); while($row = mysql_fetch_object($sql)) { // Send the emails in this loop. $member_name = $row->FirstName; if(!empty($row->LastName)) { $member_name .= ' '.$row->LastName; } if($row->MailType == 'html') { $mailer->Body = str_replace('{MEMBER_NAME}', $member_name, $htmlBody); $mailer->IsHTML(true); $mailer->AltBody = str_replace('{MEMBER_NAME}', $member_name, $textBody); } else { $mailer->Body = str_replace('{MEMBER_NAME}', $member_name, $textBody); $mailer->isHTML(false); } $mailer->Send(); $mailer->ClearAddresses(); $mailer->ClearAttachments(); $mailer->IsHTML(false); echo "Mail sent to: $member_name
"; } ?>

PHP Mailing List Code Breakdown

Let's break this code down for further understanding.

The first portion is just like our basic example earlier in this tutorial. It includes the scripts we need to instantiate the class.



Next, we will go ahead and file_get_contents() function to read these into the script, but to keep it simple here, we just use a small string instead.

Notice the {MEMBER_NAME} placeholders that I have put into these examples. Later when we loop through the users, we'll str_replace() this with their actual information.

// Setup body
$textBody = "Dear {MEMBER_NAME},nnCheck out PHP Freaks: http://www.phpfreaks.comnnSincerely,nAdmin";
$htmlBody = "Dear {MEMBER_NAME},

Check out PHP Freaks: http://www.phpfreaks.com

Sincerely,
Admin";

Next, we will go ahead and get our Mail class ready:

// instantiate the class
$mailer = new FreakMailer();

Now, this is where you will have to create your own tables and get your own data. This is a simple mysql_fetch_object()

// Get the user's Email
$sql = mysql_query("SELECT FirstName,LastName,EmailAddress,MailType FROM users WHERE 1");

while($row = mysql_fetch_object($sql))
{

Now, this is where the heart of the E-Mail sending occurs. This is extremely important for you to pay attention here. The first portion of the code will basically create the $member_name string which will contain this specific user's information for this portion of the loop.

    $member_name = $row->FirstName;
    if(!empty($row->LastName))
    {
        $member_name .= ' '.$row->LastName;
    }

Our Mail preferences. If the user's MailType is set to 'html' in the database, then we'll send them an HTML E-Mail with a plaintext alternative body. Otherwise (else) we'll send them just a plain text E-Mail.

    if($row->MailType == 'html')
    {
        $mailer->Body = str_replace('{MEMBER_NAME}', $member_name, $htmlBody);
        $mailer->IsHTML(true);
        $mailer->AltBody = str_replace('{MEMBER_NAME}', $member_name, $textBody);
    }
    else
    {
        $mailer->Body = str_replace('{MEMBER_NAME}', $member_name, $textBody);
        $mailer->isHTML(false);
    }

Please analyze the code above until you understand it. This information was previously discussed in this tutorial and you should be familiar with how to send Plain Text and HTML E-Mails.

Finally, we send out the E-Mail and then clear the addresses from the $mailer object as well as any attachments you may have.

    $mailer->Send();
    $mailer->ClearAddresses();
    $mailer->ClearAttachments();
    $mailer->IsHTML(false);
    echo "Mail sent to: $member_name
";

NOTE:
Please make sure that you use the ClearAddress() and ClearAttachments() functions otherwise the users in the Mailing list will always be appended to the list. Trust me on this one!

Summary

This tutorial should have given you a good push in the right direction to making life easier with sending E-Mail through PHP. Thanks to the excellent PHPMailer class and the developers of it, we can now send E-Mail without memorizing or constantly looking up headers when we need to send more complexe E-Mails.

If you set this Mail portions and move on to more complicating things without wasting your time.

PHPMailer Resources

I hope you take the PHPMailer FAQ. It is important to understand this class and read what the Developers have said about it. In addition, there is another great tutorial and some examples for PHPMailer on their website. Good luck!-phpfreak

PHP

 

 

Comments