Example of Using PhpMailer to send emails in PHP

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

PHP has a default mail() function for sending out emails.  However, the open source PHPMailer Library is much more easier to use.  You don’t have to construct the mail headers yourself, and hence is less error prone.

You can download the PHPMailer library from GitHub here and place within your webapp directory that you can reference.  We placed the files inside a sub-folder called phpmailer.

Here is example of using the PHPMailer to send emails …

Using PHPMailer

Using PHPMailer

1.  First we reference the PHPMailerAutoloader.php file that was downloaded.  This file contains the  PHP magic function __autoload() that will autoload the class definitions as needed.

2. And we will need it when we instantiate the PHPMailer class.

3. Once instantiated an instance into $mail variable.  We can use it to set the sender as shown.

4.  And set the receiver.  The second parameter to the addAddress function is optional.

5. Set the reply-to address.  This is the address that goes to when the receiver hits the reply button.

6. You can add CC and BCC if you like.  And you can add them multiple times.

7. Set as HTML email.  All modern email clients are able to received HTML emails now.  So this is almost always used.

8.  Compose your email and put in your Subject and Body.  The AltBody is the plain text version that receiver would get if they can not receive HTML emails.  This AltBody is option.

9.  Add attachment if you like by providing the path to the file on the server.

10.  Then send the mail with the send() function.  It it returns falsy, that means it was not able to send for some reason.  You can figure out the reason with $mail->ErrorInfo.

PHPMailer can use SMTP as well.  Sitepoint has a good article on that.