Ok, so you have an SMTP server you want to use with your WordPress to send emails. It’s a good idea, since WordPress, out-of-box, sends emails using the web server which is a really bad choice.

BTW, if you don’t know how WP sends emails and you have a WP-based site, you need to read “How WordPress Fails to Send Emails“.

If you’re a common WP user you can select one of the many SMTP plugins. To say a couple of names, WP Mail SMTP or Fluent SMTP.

But you’re not a common WP user, right? You want to super-optimize everything and another plugin to install is not what you want.

Here we are: you already have them but a little reminder doesn’t hurt:

  • the SMTP server hostname
  • the protocol (TLS, SSL) and port
  • the username
  • the password

and those lines of code to put in a file named smtp.php and uploaded to the folder wp-content/mu-plugins.

<?php
add_action('phpmailer_init', function($mailer) {
	$mailer->IsSMTP();
	$mailer->Host ='your.smtp.com';
	$mailer->Port = 587;
	$mailer->SMTPSecure = 'tls';
	$mailer->SMTPAutoTLS = true;
	$mailer->SMTPAuth = true;
	$mailer->Username = 'a username';
	$mailer->Password = 'a password';
});

I hope I don’t have to explain how it works, if you have doubts or you can’t understand it, please don’t add it to your site!

How it works

Ops…

WP has a function, wp_mail(), used by everyone to send emails. This function uses the PHPMailer library shipped with WP.

When it’s time to send something, WP fires a filter for a PHPMailer instance giving the chance to other plugins to change it (reconfigure, replace, …, there are a lot of good and bad things one can do).

The code above just attaches a function to that filter and reconfigures the PHPMailer to use and SMTP… easy. Adding the code in a file inside the folder mu-plugins, as you probably already know, creates a “must-use” plugin that is always loaded by WP (and cannot be removed without deleting the file.


Photo by Vlada Karpovich

Similar Posts

Leave a Reply