FREE THOUGHT · FREE SOFTWARE · FREE WORLD

Home  »  PHP  »  PHPMailer tutorial

by 51 comments

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

Tags

December 14th, 2006

Comments Welcome

  • Instruct Me

    Is there a way to verify what addresses PHPMailer plans to send?
    I'm on Linux where a note says, 'CC and BCC only work on Win32, not with the "mail" mailer http://phpmailer.codeworxtech.com/methods.html'

    I want to verify that the To is using the email address and the name, whereas my Cc and Bcc (which I have to use normal To anyway) are just adding the email address:

    $mail->AddAddress($To, $ToName);
    if(is_array($CcArray)){//CC and BCC only work on Win32, not with the "mail" mailer http://phpmailer.codeworxtech.com/methods.html
        foreach($CcArray as $aRecipientEmailAddress){
            $mail->AddAddress($aRecipientEmailAddress);
        }
    }
    if(is_array($BccArray)){//CC and BCC only work on Win32, not with the "mail" mailer http://phpmailer.codeworxtech.com/methods.html
        foreach($BccArray as $aRecipientEmailAddress){
            $mail->AddAddress($aRecipientEmailAddress);
        }
    }
  • Webby

    Unless I'm mistaken. I believe you forgot to run $mailer->AddAddress() to add an address in the "simple mailing list" example.

  • Sam

    Hi - good tutorial - I got as far as 'The PHPMailer Extender Class' then got lost as to what I should be doing next. I want to implement a more powerful mailer than the bformmail i am using. Have you a more expansive tutorial for implementing the php in a form?
    Sam

  • Pedro Wightman

    I only had a problem with the path of class.phpmailer.php because it was no recognized, so I had to move MailClass.inc to the phpmailer folder and make the reference directly with out a path.
    Now it works... Thanks!

  • Andy

    Nice tutorial (as always). There's probably only one point might be useful to those who need sending out email with non-English title. It usually won't work correctly without setting this line:

    $mailer->CharSet = "UTF-8";

    (the $mailer->Encoding option is only for internally displaying error message in other language).

    Just in case someone is same confused as i was.

  • Json

    Please tell me how it's possible for PHPMail to send or embed an image from a MySQL database?
    I have been searching but found nothing! Any help here would be great!

    Cheers

  • Jamarchi

    Great tutorial, I only have one question, if I write one email addres in the TO and i write 50 email address in BBC part, how many emails the server count that I have sent? 1? or 51 ?

  • Gregg

    Hi great tutorial, it helped alot thx for sharing. I love being able to use the str_replace function in the html emails. Is there any chance you could do a quick tutorial on how to use this on phpmailer FE ?

  • Zendrej

    Hi,

    I have used phpMailer in many applications of mine.

    Sometimes i get an error

    Warning: fsockopen() [function.fsockopen]: unable to connect to :25 (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. )

    I am not sure how it happens. Now in the running project also i used phpMailer, this time the above warning is always there.

    If you have any idea on this please share.

    Thanks
    rej

  • Json

    @Zendrej:
    Depends on the phpMailer version(try upgrade), maybe try the script using a different server.

    Cheers

  • Json

    Try turning off error reporting...

    // Turn off all error reporting
    error_reporting(0);
     
    // Report simple running errors
    error_reporting(E_ERROR | E_WARNING | E_PARSE);
     
    // Reporting E_NOTICE can be good too (to report uninitialized
    // variables or catch variable name misspellings ...)
    error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
     
    // Report all errors except E_NOTICE
    // This is the default value set in php.ini
    error_reporting(E_ALL ^ E_NOTICE);
     
    // Report all PHP errors
    error_reporting(E_ALL);
     
    // Same as error_reporting(E_ALL);
    ini_set('error_reporting', E_ALL);
  • Jamachi

    Great tutorial, I only have one question, if I write one email address in the TO and i write 50 email address in BBC part, how many emails the server count that I have sent? 1? or 51 ?

    Other question:
    Is necessary this part => 'First Person' ?
    $mailer->AddAddress('recipient1@domain.com', 'First Person');

  • Armitag3

    Thx for the tutorial helped me a lot.
    Just a quick question, is there a way with phpMailer to capture the email in a SQL db.

    I have a feedback/Q&A form and want to capture the feedback mails people send me in a SQL so that i can make a page where people can see what the progress is on the feedback/Q&A.

    Thx for any help in advance.
    Armitag3

  • 4guys

    Good Code.I was looking for the same for my website form.

  • Lewis

    I have been saddled with the task of sending hundreds of thousands of mails for a client in his site. I found that tinkering with the config.php for days finally allowed me to send about 2000 mails every hour. It was on a dedicated server with no resource crunch. Yet this is the maximum I could extract from the mailer. In their documentation it was mentioned that the maximum the software can do is about 3000 emails every hour.

    About 9 years ago, I wrote a no frills Perl script which managed to belt out at least 3 times this limit. Any thoughts on this limitation ?

  • Laszlo

    Hi All,

    My opinion also is this a very good tutorial.

    I have a question. I've a portal with many users. What if I want to use the mailing list (explained above in the tutorial) mail sending?

    Won't be the sender loop so slow? Of course I don't want to send big mails, but every mail will contain graphical header as company logo.

  • pradeep

    I wish send 10,000 mails/hour... can i send through php mailer function?

  • Freek

    Pfff... When you say you'll keep things simple, please do so..! Don't go off sidetracks by first talking about extender classes and stuff, that make things complicated. Noob..! :(

  • Kob-soft

    Thank you for tutorial :)

    Can help me to find out!

  • Akin A

    I logged in here yesterday for the first time looking for a tutorial and I heard this "brilliant!" song on the youtube snippet. But can you guys please let me the artist and song name so I can buy it ?

  • Mike Frejik

    I'm trying to insert php variables into my email body within a table:

    1. Do our products meet your specification?
    $enter1
    $blog1

    When I get the email it actually says $enter1 and $blog1 not the value of the variable. I've tried adding "$enter1" and '$enter1' but those don't seem to work either. What is the best way to enter the variables? Any help would be appreciated!

    Thanks,
    Mike

  • tacuster

    Some help for here

    i need setup a rate of 200mails per hour.

    how can do??

  • Ajay Nair

    Hi I have a client, who contacted me to rectify their website's PHP mail sending error on their website.

    Tehy are using,

    // SMTP - PHP SMTP class
    //
    // Version 1.02
    //
    // Define an SMTP class that can be used to connect
    // and communicate with any SMTP server. It implements
    // all the SMTP functions defined in RFC821 except TURN.

    and when i press send i am receiving

    "Error while trying to send message. Language string failed to load: from_failed"

    on the contact page and

    "Error while trying to send message. Language string failed to load: from_failed"

    on another page.

    What could be wrong?

    AJ

  • Rod Bowers

    Good tutorial but I had a problem with the body() function when composing an html message. It needs to be:

    $mailer->Body = $htmlBody;

    I need to find a solution to embedding images that are called form a database. I'd be grateful for any tutorials.

    Thanks

    Rod

  • La Roux

    Akin A - Song is Going in for the kill, by La Roux

  • wiyo

    Hallo,
    I have any question, i try to make contact form using phpmailer, all is going good, but when i try to send contact form, the email come 3 hours later in my email, what wrong i do? have you any idea? and can you help me? please!!!

    Thank you
    Best regard

  • wiyo

    Hallo,
    well i have to times, cause i don't see my question... heheheee..

    I try to make contact form using phpmailer, work for googlemail but doesn't work for msn and yahoo, what the problem, is the problem from yahoo or msn? or my server website?

    Thank you
    Best Regard

  • Dinesh

    hi,

    thank you for the tutorial. but i need to send email as html, but when i try to sent a e-mail address in the body part, it sent with an anchor tag like email@email.com. but i need it without wrapping. how can i do this?

    please reply

    Dinesh

  • phpfreak – Eric Rosebrock

    Awesome rewrite! Thank you for taking the time to re-publish this and properly give credit. You've done an excellent job and looking back at this, you followed my writing style to a T! Awesome!!

    //phpfreak

  • David

    Hi

    I tried to extend the class as shown in the example.. My purpose is the rewrite the method CreateHeader() to remove the X-mailer. So I wrote this:

    class KMailer extends PHPMailer
    {
          public function CreateHeader() {
              copy of the orriginal function without the x-mailer
     
          }
    }

    but I cannot send anything. Does anybody have an idea?? thanks in advance
    David

  • Remco

    Hello php mailer works great, but it sends two the same mails. Does anybody know why and how I can fix this? I used the example's and it sends two copy's

  • Jitesh

    How to add time intervals in PHP Mailer?

  • hardison

    I'm running WAMP server on my WindowsXP. I downloaded and extracted the PHPMailer contents to a directory. But where exactly should i place them inside WAMP directory?. Its path is F:/Wamp/ in my PC.

  • S

    Hi,
    I need to send a mailer. I have a list of emails in .txt in a file delimited by semi_colons, I have an html file from last years mailer and I have php code from the one they did last year called Mailer.

    In the tutorial you said, test the mailer by sending an email. Well, how do I send an email from PHP.

    I have ftp access to the server and that's about it, I don't even see the mailer.php on the server. Where on the server should I put mailer.php and how do I 'execute' it to see if it actually emails.

    Then of course, how do I get it to read the 400 names in the text file. Thanks for any help just to get started in the right direction

  • Mr.Baka

    thanks, it's very nice. I done my first php program with it. Mail2Blogger.

  • Robert

    is there a way of just sending the subject line with an empty body?
    if i leave the $mail->Body = " "; empty i get an error message: email empty!?

  • Lynn Greene

    I've got a distribution list of approximately 1500 e-mail addresses.

    I've implemented PHPMailer, and I receive an error after successfully sending the e-mails out to exactly 900 addresses.

    I've checked with my hosting company who tells me that they have no restrictions.

    Any idea what I have to do to getthe rest sent out?

  • benya

    hi,
    I have aproblem when using the php mailer class.
    my message is being sent but unfortunately the email received contains the carriage returns and thus line breaks are not being interpreted.
    e.g HirnPlease
    what do i need to change to make this work

  • pravin kumar

    In "PHP Mailing List Example", I dont see "AddAddress" method used anywhere.
    Please explain or rectify the code for it.

    Also, explain some more about "ConfirmReadingTo" method. Does it work in all the environment?

  • marcin

    Same as pravin kumar: "In "PHP Mailing List Example", I dont see "AddAddress" method used anywhere. Please explain or rectify the code for it".

  • Froos

    I followed this "course" and succeeded in obtaining: the "mail sent" answer.
    The next thing I wanted to insert were the following lines:

    // 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...

    Then I got lost. Whithout "$mailer->isHTML(true);" and a simpel body and the instruction: $mail->Body = ".........."; everything runs smootly.
    The moment I insert "$mailer->isHTML(true);" I got a blank
    How??

  • alchemyst_18

    Hi!

    I just want to ask if the receipt of the email sent can reply back to the sender? (Email will be send at back the system)

    Thanks!

  • Urassis Draggin

    NICE ! ...Good write-up, Thanks !

    I did not see a version this is based on ... latest stable is 5.2.1. Essentially reiterating Froos ~, One thing is not consistent or correct, at least with v5.2.1, basic (core) example, you show mailer Body as a variable, you assign a string for message. In the HTML section (including alternate text), you present both Body and AltBody as functions - using parentheses, as if the variable(s) previously defined ($AltBody | $htmlBody) passed as parameter(s). This could easily throw a user reading this (as it did me at first - I received an error stating that 'Body is not a function'), who is copying your text verbatim. I think what you want is to replace the parentheses with an equals sign (=): $mailer->Body = $htmlBody. At least this worked for me.

    Also, I like your use of the placeholder (MEMBER NAME) and then replacing that with actual name, rather than constructing the message in sections. Nice.

    In any event, I looked for something like this on the web and found very little so, THANKS!

  • Pascal Boulerie

    @alchemyst_18

    just look at the section "Adding a Reply-To Address"

  • Pawan Kumar

    I am unable to send CC Mail in PHP Mailer

  • Pawan Kumar

    I am unable to send CC Mail in PHP Mailer

  • BigBro

    How do I limit the file size for being sent out through PHPMailer? Is there any built-in feature that I can use? If yes, then how? Any example for this is much appreciated.

  • Davmar

    How do I take out the email header message after my email has been sent successfully?

  • rahjiggah

    I am sending to groups of people, if one email recipient is bad, it stops midway and doesnt send to the rest of the list, any idea how to ignore a bad email recipient response?

  • Tom

    I am confused to :D

    adding "$mailer->CharSet = "UTF-8";" doesn't make it send non-English characters :(

    Seems to really be only for internally displaying error messages...


Related Articles


My Online Tools
Popular Articles


Hacking and Hackers

The use of "hacker" to mean "security breaker" is a confusion on the part of the mass media. We hackers refuse to recognize that meaning, and continue using the word to mean someone who loves to program, someone who enjoys playful cleverness, or the combination of the two. See my article, On Hacking.
-- Richard M. Stallman









[hide]

It's very simple - you read the protocol and write the code. -Bill Joy

Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution 3.0 License, just credit with a link.
This site is not supported or endorsed by The Apache Software Foundation (ASF). All software and documentation produced by The ASF is licensed. "Apache" is a trademark of The ASF. NCSA HTTPd.
UNIX ® is a registered Trademark of The Open Group. POSIX ® is a registered Trademark of The IEEE.

+Askapache | askapache

Site Map | Contact Webmaster | License and Disclaimer | Terms of Service

↑ TOPMain