Introduction
If you're hosting a WordPress website you'll likely need to configure some type of email delivery service; whether it's Mailgun, Postmark, SendGrid, or another service. Being able to send emails is an important part of your WordPress website's functionality and you need some way of making sure the messages being submitted through your contact forms are ending up in the correct inbox.
There are a number of plugins you can use to connect your website to the service of your choosing, such as WP Mail SMTP by WPForms. Maybe the service you're using even has it's own plugin.
I personally prefer to set things up directly in the code. This allows you to more easily control your configuration on different environments.
Hooking things up
You can start by adding the following phpmailer_init
hook to your theme's functions.php
file. The phpmailer_init
action hook allows you to easily hook into the phpmailer object and pass in your own arguments. For more information about that be sure to check out the WordPress Developer Resources
php
Connecting to your email service
Now all you need to do is add some values to your wp-config.php
to connect your website to the service of your choice.
Note: the code we put in the functions.php
does assume that you define all the constants shown below.
bash
You're done! Now you can send as many emails from your website as your heart desires. Just make sure you're being responsible and not sending spam!
Wrapping up
The reason I like this method is because it provides a little more flexibility to set things up on different environments. I use Postmark as my email delivery service for all production websites. However, I use Mailtrap for all websites that are in a development or staging environment so that I'm not bugging clients when testing out new features or troubleshooting issues.
This setup makes it easy to have separate configurations on different environments because it's relying on information in your wp-config.php
instead of your website's database.
Was this post helpful?