Assume we have blank WP site and we want to setup SMTP settings programmatically in our plugin or theme. What’s the easiest way to do it without changing core files?
Leave a Reply
You must be logged in to post a comment.
Assume we have blank WP site and we want to setup SMTP settings programmatically in our plugin or theme. What’s the easiest way to do it without changing core files?
You must be logged in to post a comment.
First of all, if we take a look at implementation of
wp_mail
function, we will see that this function usesPHPMailer
class to send emails. Also we could notice that there is hard coded function call$phpmailer->IsMail();
, which sets to use PHP’smail()
function. It means that we can’t use SMTP settings with it. We need to callisSMTP
function ofPHPMailer
class. And also we need to set our SMTP settings as well.To achieve it we need to get access to
$phpmailer
variable. And here we come tophpmailer_init
action which is called before sending an email. So we can do what we need by writing our action handler:And that’s all.
Addition to @EugeneManuilov answer.
SMTP settings
By default those can only get – as @EugeneManuilov already answered – be set by during a callback attached to an
do_action_ref_array()
. Source/core.SMTP Exceptions
Per default WordPress doesn’t give you any debug output. Instead it just returns
FALSE
if an error occurred. Here’s small plugin to fix this:Repository
The plugins are both available in this Gist on GitHub, so consider checking those plugins out from there to grab any updates.
The other answers to this post, while providing a working solution, don’t address the security issue of storing your SMTP credentials in a plugin file or functions.php. In some cases that may be OK, but best practices would dictate storing this information in a more secure fashion. There’s really not a good reason to not follow best practices when it comes to protecting your credentials.
Some would suggest saving it to the DB as an option, but also provides the same security issues depending on the number of administrative users your site has and whether those users should be able to see these login credentials. This is also the same reason to not use a plugin for this.
The best way to do this is to define constants for the phpmailer info in your wp-config.php file. This actually has been discussed as a feature in the Mail Component, but hasn’t been accepted as an actual enhancement at this time. But you can do it yourself by adding the following to wp-config.php:
Once these are defined in wp-config.php, they can be used anywhere by using the defined constant. So you could use those in a plugin file or in your functions.php. (Specific to the OP, use a plugin file.)
There is a little more detail on this in this post and a gist on github here.