Do something after sending email

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.

Leave a Comment