This tutorial describes how to use PHPMailer Pro and explains the use of the class functions.

Contents

  1. PHPMailer Pro What is it? What does it do? Who needs it? Brief examples of PHPMailer Pro features.
  2. First time
    Sending your first email with PHPMailer Pro.
  3. Using Attachments
    Sending mails with file attachments: filesystem, database or inline.
  4. Using HTML Mail
    Using the class’ integrated HTML Email features.
  5. Support: Where do I get help?
    How to find support resources: PHPMailer Pro website, mailing list etc.
  6. Other Resources Email and PHP Resources
    There is a lot of information in the net about email, and PHP.

PHPMailer Pro

PHPMailer Pro is a PHP email transport class that provides the functionality to send emails. The two primary features are sending HTML Email and emails with attachments. PHPMailer Pro supports nearly all possible mail transport agents (MTA) to send email: Sendmail and all MTAs that include a Sendmail wrapper (includes Postfix, Qmail, Exim, etc) & direct to SMTP server. You can use any feature of SMTP-based emails, multiple recipients via to, CC, BCC, etc. In short: PHPMailer Pro is an efficient way to send emails within PHP.

Anyone can use PHP mail() to send emails. PHP mail() is complex, finicky, not well documented, and very frustrating to use and debug. And nearly impossible to add attachments of any kind. And PHP mail() is limited to text only without exotic coding. PHPMailer Pro to the rescue. PHPMailer Pro is an easy process to send email, makes it possible to attach files, send HTML email, etc. With PHPMailer Pro you can even use your own SMTP server and avoid PHP mail() and Sendmail routines used by the PHP mail() function.

This tutorial explains how to implement the class into your script or website and how to build an email application. Please note: if you just want to send simple emails and you have no problems with the mail() function, continue to use mail(). And likewise, if you are using PHPMailer, SwiftMailer, or any other mailer automation script, continue using those. I created PHPMailer Pro to simplify sending emails and address the needs of those programmers looking for an easy to use solution and those looking for a lighter footprint.

First time

For those who have not used PHP’s mail() function before, this section will provide information about email and emailing in general, in addition to explaining how to get started with PHPMailer Pro.

Before continuing, please be sure that PHPMailer Pro is installed correctly. If you feel uncertain, please read the installation instructions that accompany the package. If you’re still not sure, you can verify that you’ve installed PHPMailer Pro correctly with this script:

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require('PHPMailer Pro.php');
$mail = new codeworxtech\PHPMailer Pro();
?>

Save it as a PHP document in the same directory where you’ve saved PHPMailer Pro.php. If no errors result from running the script, your installation has been done correctly. The first three lines set your script to show all errors.

The last two lines are the snippet of code is also the start of any use of PHPMailer Pro. require("PHPMailer Pro.php"); includes the source code of the class and $mail = new codeworxtech\PHPMailer Pro(); creates a new instance of the class the class as $mail. All features, functions and methods of the class maybe accessed via the variable (object) $mail.

Creating an instance of the class is only the first step, of course. Let’s go ahead and send out the first mail. For this you’ll require the basics: An recipient address, a from address, a subject and the text of the message.

PHPMailer Pro has automated the process of selecting the method of delivery. Unless you plan to use SMTP, you do not need to use a PHPMailer Pro property to choose a method. When you start PHPMailer Pro, the first part of the process is to query the server it is running on to determine the method to delivery your mail, and the port to use. You can override this if you want to use SMTP or a different port.
Note, by the way, Sendmail is the most popular MTA.

If you plan on using SMTP, please be aware that PHPMailer Pro has created a new SMTP class ... it is still heavily influenced by the one of the grand SMTP classes originally authored by Chris Ryan.
When using SMTP, you’ll need a valid SMTP server; this may well be the same one that you use in your personal mail client.

Having gathered the necessary information to send your first email, you’d use that information in place of the examples provided here:

Basic Example
<?php

require('PHPMailer Pro.php');

$mail = new codeworxtech\PHPMailer Pro();

try {

  $mail->SetSender( [ "from@example.com" => "Your Name" ] );

  $mail->AddRecipient( [" myfriend@example.net" => "Friend Name" ] );

  $mail->Subject     = "First PHPMailer Pro Message";
  $mail->MessageText = "Hi! \r\n\r\n This is my first email sent through PHPMailer Pro.\r\n\r\n";

  if ($mail->Send()) {
    echo 'Message has been sent.';
  }
} catch (Exception $e) {
  echo $e->errorMessage();
}
?>
SMTP Example
<?php

require('PHPMailer Pro.php');

$mail = new codeworxtech\PHPMailer Pro();

try {

  $mail->SMTPHost       = "mail.yourdomain.com";
  $mail->SetSMTPAccount( [ "yourname@yourdomain.com" => "yourpassword" ] );

  $mail->SetSender( [ "from@example.com" => "Your Name" ] );

  $mail->AddRecipient( [" myfriend@example.net" => "Friend Name" ] );

  $mail->Subject     = "First PHPMailer Pro Message";
  $mail->MessageText = "Hi! \n\n This is my first email sent through PHPMailer Pro.";

  if ($mail->Send()) {
    echo 'Message has been sent.';
  }
} catch (Exception $e) {
  echo $e->errorMessage();
}
?>

Note the use of try {} and catch {} in the examples. PHPMailer Pro uses PHP Exceptions for error handling (by default). The best way to use these, or "catch" the exceptions is with the use of the try-catch PHP commands.

Save these as a php files and change the values to your values, of course. Here is an explanation of what each element in these scripts do, starting with the Basic example:

Enter the address that the email should appear to come from. Must be valid email address. The Name portion at the end is optional.
$mail->SetSender( [ "from@example.com" => "Your Name" ] );

The next parts are the email you are sending, starting with the recipient, that is who you are sending the email to. You must use a valid email here, of course, if only so that you can verify that your PHPMailer Pro test worked. It’s best to use your own email address here for this inintial test. As with the "SetSender" field, you may provide a name for the recipient:
$mail->AddRecipient( [" myfriend@example.net" => "Friend Name" ] );
alternately, without a name:
$mail->AddRecipient( [" myfriend@example.net" ] );

Setting the subject and body is done next:
$mail->Subject = "First PHPMailer Pro Message";
$mail->MessageText = "Hi! \r\n\r\n This is my first email sent through PHPMailer Pro.\r\n";

As the last part of the try{}, we send out the email. This is done with if ($mail->Send()) {. In this example script, it’s combined with an success message; if Send() succeeds, it’ll return true and display: echo 'Message has been sent.';.
The last part would catch any error generated by PHPMailer Pro’s Exception error handling.
catch (Exception $e) { will catch any errors and echo $e->errorMessage(); will display the error(s).

The SMTP example, explained:

The only difference between the Basic example and the SMTP example is the group of properties that tell PHPMailer Pro to use SMTP as the transfer agent. It is that simple.

Setting smtp.example.com as the SMTP server. Just replace it with your own SMTP server address. You can even specify more then one: separate them with a semicolon (;): "smtp.example.com;smtp2.example.com". If the first one fails, the second one will be used, instead.

Attachments

Often attachments are needed in emails. They may be files like images/photos, videos, application files like spreadsheets, PDF documents, or compressed zip files. Maybe you need to send multiple attachments.

There are three ways of sending attachments with your mail: 1) attach a file from the filesystem; 2) attach data from a PHP variable; or, 3) embedded in the body of the email. The second option is called a StringAttachment. This makes it possible put extract data from a database and attach it to an email, without ever having to actually save it as a file.

File Attachments

The property to attach a file can be placed anywhere between $mail = new codeworxtech\PHPMailer Pro(); and !$mail->Send(); and it’s called AddAttachment($path);. This single line will add the attachment to your mail.

$path is the path of the filename. It can be a relative one (from your script, not the PHPMailer Pro class) or a full path to the file you want to attach.

If you want more options or you want to specify encoding and the MIME type of the file, then you can use three more parameters, all of which are optional:
AddAttachment($path,$name,$encoding,$type);

$name is an optional parameter, used to set the name of the file that will be embedded within the email. The person who will recieve your mail will then only see this name, rather than the original filename.

$encoding is a little more technical, but with this parameter you can set the type of encoding of the attachment. The default is base64. Other types that are supported include: 7bit, 8bit, binary & quoted-printable. Please refer to your SMTP documentation about encoding and the differences between types. In general, mail servers will convert encodings they don’t want to handle into their preferred encoding type.

$type is the MIME type of the attached file. Content types are defined not necessarily by file extensions (i.e., .GIF or .MP3), but, rather, a MIME type (Multipurpose Internet Mail Extensions) is used.

String Attachments

String attachments works much like AddAttachment(), and is called with AddStringAttachment($string,$filename,$encoding,$type). The string data is passed to the method with the first parameter, $string. Because the string will become a standard file (which is what the attachment will be when received via email), the $filename parameter is required. It’s used to provide that filename for the string data.

The rest is just the same as described in detail above.

So, why use AddStringAttachment instead of AddAttachment? Is it for text-only files? It’s primarily for databases. Data stored in a database is always stored as a string (or perhaps, in the case of binary data, as as a BLOB: Binary Large OBject). You could query your database for an image stored as a BLOG and pass the resulting string to the AddStringAttachment.

Inline Attachments

There is an additional way to add an attachment. If you want to make a HTML email with images incorporated into the body, it’s necessary to attach the image and then link the <img src="cid:CID" /> tag to it. For example, if you add an image as inline attachment with the CID my-photo, you would access it within the HTML email with <img src="cid:my-photo" alt="my-photo" />.

In detail, here is the function to add an inline attachment:
$mail->AddEmbeddedImage(filename, cid, name);

By using this function with this example’s value above, results in this code: $mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');

For more Information about HTML Email, see the section Using HTML email.

Handling Attachments

If you want to attach multiple files (or strings), just call AddAttachment() or AddStringAttachment() multiple times. All attachments (file, string, and inline) may be stripped from an email by invoking ClearAttachments().

Using HTML Email

Sending out HTML email is a simple enough task with PHPMailer Pro. Mail clients vary greatly in their rendering of HTML email, with some refusing to show it entirely. For those mail clients which are not able to display HTML, you can provide an alternate email body containing the message as plain text.

First we’ll create a basic HTML message:

<?php

require('PHPMailer Pro.php');

$mail = new codeworxtech\PHPMailer Pro();

try {

  $mail->SetSender( [ "from@example.com" => "Your Name" ] );

  $mail->AddRecipient( [" myfriend@example.net" => "Friend Name" ] );

  $mail->Subject     = "An HTML Message";
  $mail->MessageHTML = "Hello, <b>my friend</b>!<br><This message uses HTML entities!br>";

  if ($mail->Send()) {
    echo 'Message has been sent.';
  }
} catch (Exception $e) {
  echo $e->errorMessage();
}

?>

It’s as easy as creating a plain text email. Use a string with embedded HTML for $mail->Message.

The example above will be sent out containing both text and HTML (the HTML "body" will be converted to text for the second part). This is the automated way of handling conversion and is perfect when both the text and HTML messages are the same. You may want different messages, however. So there is an alternative way of doing that. Specify the text portion after MessageHTML. That would look like: $mail->MessageHTML = "Hello, <b>my friend</b>!<br><This message uses HTML entities!br>"; $mail->MessageText = "Hello, my friend!\nThis message uses HTML entities, but you prefer plain text!\n"; to set the alternative body (MessageText in short).

And that’s how to create an HTML email. Apply the send method and the mail will be sent.

If you want to send out a HTML email with pictures, Flash animations or whatever else, PHPMailer Pro supports this as well.

Please note that it is not possible to send anything but pure W3C compliant HTML inline with your emails. That means no javascript, jquery, scripts of any kind, no Flash, etc. ... these can be included as attachments, but not as inline viewable objects – other than images (JPG, JPEG, PNG, & GIF). While some email clients may be able to display some objects such as other image types, many email clients will either block them, crash, or remove them entirely as inline objects.

Support - Where do I get help?

PHPMailer Pro is open source. Most of the questions are answered within this tutorial, but some questions may remain. PHPMailer Pro has its own homepage on SourceForge and you can request support there.

Other Resources to email and PHP

There’s an enormous amount information avaiable about email, PHP and PHPMailer Pro:

PHP mail() function reference
http://www.php.net/mail

Standard email RFC 822
http://www.w3.org/Protocols/rfc822/

MIME email RFC 2046
http://www.ietf.org/rfc/rfc2046.txt

SMTP RFC 821
https://tools.ietf.org/html/rfc821