Do something after sending email

I want to do something after WordPress sent an email. For example, after sending “Reset Password” email using wp_mail() function.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Using the PHPMailer class with an action callback:

I did some digging into the PHPMailer class and found that it supports a custom action.

Here’s how the callback is activated with the doCallback() method in the class.

There’s also a PHPMailer test on GitHub using this feature via the callbackAction() callback.

We can set it up in WordPress with:

$phpmailer->action_function = 'wpse_mail_action';

where wpse_mail_action() is the action callback.

Here’s an example how we can apply this:

/**
 * Custom PHPMailer action callback
 */
function wpse_mail_action( $is_sent, $to, $cc, $bcc, $subject, $body, $from )
{
    do_action( 'wpse_mail_action', $is_sent, $to, $cc, $bcc, $subject, $body, $from );
    return $is_sent; // don't actually need this return!
}

/**
 * Setup a custom PHPMailer action callback
 */
add_action( 'phpmailer_init', function( $phpmailer )
{
    $phpmailer->action_function = 'wpse_mail_action';
} );

Now we have access to the wpse_mail_action hook.

We could then add our own mail logger and check if the mails were successfully sent or not.

Example:

Here’s an (untested) example how we could do something after “Password Reset” posts are sent:

/**
 * Do something after the "Password Reset" post has been successfully sent:
 */
add_action( 'wpse_mail_action', function( $is_sent, $to, $cc, $bcc, $subject, $body, $from )
{
    if( $is_sent && false !== stripos( $subject, 'Password Reset' ) )
        // do stuff

}, 10, 7 );

where we could add some further restrictions and wrap into other actions if neccessary, like the retrieve_password hook.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x