When it comes to sending emails in WordPress, the wp_mail function and its related filters such as
wp_mail_from_name are usually enough to accomplish the majority of what we need.
But there are times where it’s not enough. Specifically, there are times where we may need to define the details for using a custom SMTP server in WordPress.
Fortunately, WordPress provides a hook that makes this really easy to do.
Setting an SMTP Server in WordPress
So let’s say that you’re working on a web site or web application and you want to relay the email through a custom SMTP server rather than, say, whatever is installed on the server on which the site is running.
To do this, you need at least six pieces of information:
- The SMTP host address
- Whether or not you want to use SMTP authentication
- The SMTP port
- The username for the SMTP server
- The password for the SMTP server
- And whether or not you want to use a secure connection to the SMTP server
You can also specify the
from and the
fromName properties using the method I’m about to show; however, I prefer to use the provided action hooks for doing this.
Hook It Up in the Constructor
So first, let’s say that we have a constructor that’s responsible for setting up various hooks related to the email as well as that of the SMTP server.
The initial class may look something like this:
If you’re familiar with the
wp_mail function, then most of these hooks are likely familiar; however, the
phpmailer_init may be one that you haven’t seen before.
This is where the SMTP settings are defined.
Define The Hooks
Along with defining functions for the rest of the hooks, this is where we can set the SMTP server credentials to be used:
The code should be relatively easy to follow (and I’ve covered this in more detail in a previous post); however, the most important thing to note in this particular block of code is the values of the properties that are set on the instance of
This is what allows us to use a different SMTP server.
The Working Class
Finally, the full version of the code looks something like this.
Obviously, this is meant to be invoked by a third-party object such that you’ll need to pass the
$message of the email to the
send() function, but the rest of the code shows how to specify to whom the email is being sent, the subject line of the email, and what SMTP server we’re using to relay the messages.