How to send custom emails using wp_mail() and overwrite all WordPress registration emails.
In this quick tutorial, I will show you how to send custom emails to your registered users using the wp_mail() function.
So, let’s not waste anymore time and dive right into it.
See here a custom new registration email I have created for one of my sites using the approach below.
First, you need to have some kind of generic HTML template for your emails.
Not going into much detail here but there are a couple of tips while you code your HTML template.
Note: You can have as many different email templates, for the sake of simplicity for this tutorial I decided to go with one generic template for all of our emails. It is still flexible but if you need more you have to create/load multiple templates.
Once we have our email template we need to create a couple of functions to handle how we send our emails.
The first function would be used to send any email within your system, you can specify an email address if you want to send an email to non-registered users. By default, this function will look for a WordPress user.
The second function would be used to overwrite existing email functionality like new user registration or password reset emails.
Note: I tried to keep these functions as simple as possible so you can extend and customize them to meet your needs. However, the same approach could be applied to many different scenarios.
Now we are all set up and ready to use our newly created custom email feature. To do that we need to create a couple of action hooks.
The first one would use our compose_email() function and will overwrite an email when a registered user requests a password reset within our system. And the second action will overwrite the email when we have a new user registration.
Both actions are very similar the only difference is that we need to create and then return the new email contents when we overwrite the existing WordPress functionality for new user registration.
Note: We need to also specify the content type for our emails, which in our case is text/html. By default WordPress is set to send text-only emails.
Bonus: In some cases, you may want to disable system emails sent on password change to avoid duplicates.
add_filter('send_password_change_email', '__return_false', 10, 1); // users
add_filter('send_email_change_email', '__return_false', 10, 1); // admin
You can use the above approach to send custom emails anywhere within your system. I didn’t have an example in this tutorial but you can use the compose_email() function without having it to rely on any WordPress existing functionality or have registered user.
‘Til the next time.
* We have a NO SPAM policy so you won't reaceive any meaningless emails from us!