Send HTML Emails with the PHP PEAR Mail Library
Sending emails in HTML format within your web applications is a necessity. Whether you're a blog with marketing and newsletter subscription needs or a full-fledged eCommerce site handling transactional data, you'll need functionality behind it to submit emails successfully to all your users.
This article walks you through setting up the PEAR Mail library within your PHP installation on a Ubuntu server, adding the ability to send HTML emails via SMTP. It will also teach you how to add multiple recipients as well as add attachments to your emails.
What is PEAR?
Simply put, PEAR, or PHP Extension Application Repository for short, is a repository of PHP software code and libraries.
PHP prides itself on providing a solid functionality case while also maintaining its lightweight architecture. However, there are some instances where you can expand on that pre-built functionality.
In the event of sending HTML emails with PHP, PEAR is a perfect solution.
How to Install PEAR and the PEAR Mail Library
Assuming you already have PHP installed on a Ubuntu instance, let's start with adding onto it with a PEAR installation.
Open up your command-line tool and enter the following command to update your server to the latest packages:
sudo apt-get update
Now that your packages are updated, let's install PEAR for PHP:
sudo apt-get install php-pear
Now, if you type pear
in your command-line tool and press the Enter key, you should see a list of available commands within PEAR. If you don't, something is wrong with your installation and you'll need to troubleshoot.
The final step for your PEAR installation is to setup PEAR to use the Mail library by entering this command:
pear install --alldeps Mail
And, if you'll be adding attachments to your emails, make sure to also install the Mail_Mime
extension:
pear install Mail_Mime
In the rest of the article, we'll go through each of the steps to configure and submit custom emails to your website users, as well as best practices to follow when submitting emails.
1. Include the PEAR Mail Library
Now we'll concentrate on creating the PHP script in your application.
First, you'll need to include the newly installed PEAR Mail library with the following line of code:
require_once "Mail.php";
You do not need to modify the include path for this library to work. Doing so generally throws an exception. Simply including as "Mail.php" will work anywhere within your web application.
If you'll be adding attachments to your emails, you'll also need to include the following mime.php library file:
require_once "Mail/mime.php";
2. Set your Email Headers
Second, we'll need to define a set of headers in an array:
$headers = [
"From" => "hello@orangeable.com",
"To" => "hello@orangeable.com",
"Reply-To" => "hello@orangeable.com",
"Subject" => "Test Email",
"Content-Type" => "text/html"
];
Here, we're defining the from and to email addresses for the email submission, as well as the correct address to reply to. And we're including a custom subject line so the email subject isn't blank when users receive it.
We're also including the content type of the email. The default is plain text, so if you want to send emails containing HTML content, you'll need to change the content type to "text/html".
If you would like to copy additional recipients to this email, you can do so with either the Cc
or Bcc
attributes within the $headers
object. In doing so, just make sure that you're providing a comma-delimited list of email addresses like this:
$headers["Cc"] = "email@one.com,email@two.com";
$headers["Bcc"] = "email@one.com,email@two.com";
3. Configure your SMTP Settings
Third, we need to configure our SMTP variables by setting two arguments in the Mail::factory
method.
$stmp = Mail::factory(
"smtp",
[
"host" => "my.smtp.host",
"username" => "smtp-username",
"password" => "smtp-password",
"port" => 587,
"auth" => true,
"html" => true
]
);
Here, we're assigning the $stmp
variable to our Mail::factory()
object, readying it for email submission in the next step.
The first argument is set to the value "smtp" because we'll be sending emails via an SMTP server. The second argument is an array, defining our SMTP server settings.
You'll just need to make sure that you change out your variable assignments to the correct values that match your SMTP server settings.
If you don't know your SMTP server settings, check with your hosting provider. Most hosting providers provide an SMTP server as part of their package as long as you're a customer with them.
4. Send an HTML Email
In the last step, we'll be sending our HTML email with the PEAR Mail library's Mail::send()
method:
$body = '
<h1>This is a test email</h1>
<p>This is to test HTML within our emails.</p>
';
$mail = $stmp->send(
"hello@orangeable.com",
$headers,
$body
);
For the first argument of the Mail::send()
method, we're attaching the email address, or addresses, we'll be sending our email to. The second argument is our $headers
array we created earlier, and the final argument is our message body.
The message body can be in HTML format and you can include any styling methods you want within your emails, as long as your email styling abides by the guidelines.
Assigning a variable to your Mail::send()
method is not required, but available to view and debug email submission responses from the SMTP server.
var_dump($mail);
5. Add Email Attachments
There is some additional code required if you'll be adding attachments to your emails:
$file = "[path-to-file]";
$mime = new Mail_mime();
$mime->setHTMLBody($body);
$mime->addAttachment($file, "application/octet-stream");<br>
We started by setting the path to the file we would like to attach to our email. Then we invoke the Mail_mime()
extension, save the HTML in our $body
variable to the $mime
object, then attach the file.
When attaching files, make sure to use the application/octet-stream MIME type. This MIME type is used for unknown binary files and ensures that the file gets added to the email as a downloadable attachment instead of included in the body.
Next, we need to add the headers from our $mime
object to our $headers
object:
$body = $mime->get();
$headers = $mime->headers($headers);
Other Useful Tidbits
- You can send email to multiple recipients at once by changing the to value in your
$headers
variable and first argument of theMail::send()
method to a comma-delimited list format of valid email addresses. - You can copy other users on email submissions by including the Cc and Bcc objects within the
$headers
variable, as explained earlier. If you want to copy multiple recipients at once, you can do so in a comma-delimited list format.
Bcc tends to be unreliable in older versions of the PEAR Mail library. Make sure you're using the latest version on your server and test this option thoroughly.
Important Note: Some hosting providers, like AWS' Simple Email Service, require that you verify your domains and email addresses before sending emails out. Check with your hosting provider to make sure that this is done properly before you start submitting emails through their servers.
Email Submission Best Practices
This isn't related to email submission functionality but should be mentioned to cover a few email etiquette points.
- Make sure you clearly describe who you are and what you're presenting to your users in your emails. Sending garbage will result in complaints that could get you permanently banned by your SMTP server provider.
- An email should only be submitted to users who are expecting it. Popular example types include when they've placed an order on your website, they should receive an order confirmation email. Or if they've signed up to your mailing list or newsletter, they would expect to receive updates from you via email on a regular basis.
- In cases where you submit emails to users who have signed up for your newsletter or mailing list, you should always provide a way to unsubscribe from the distribution lists easily. Clearly displaying a link at the bottom of your email with the title "Unsubscribe" is a good way to handle this. Make sure this link works properly.
Conclusion
Now, you should be able to send HTML emails to all of your users and do it correctly. There's a little bit of setup involved, but it should only take a few minutes to get up and running when sending HTML emails with PHP PEAR.
This was the easiest implementation for my current setup. You're also able to use PHP's built-in mail()
function, I just didn't find that it had all of the bells and whistles that come with the PHP PEAR Mail Library.
Comments
Lindsey John