2

Is there a conditional check I can run for phpmailer_init or a wp_mail parameter that let's me apply my custom phpmailer_init SMTP settings only on specific wp_mail actions or does phpmailer_init always run sitewide?

4

phpmailer_init will always fire for every wp_mail() call - however, you can hook/unhook it conditionally like so:

function wpse_224496_phpmailer_init( $phpmailer ) {
    // SMTP setup

    // Always remove self at the end
    remove_action( 'phpmailer_init', __function__ );
}

function wpse_224496_wp_mail( $mail ) {
    // Example: only SMTP for emails addressed to foo@example.com
    if ( $mail['to'] === 'foo@example.com' )
        add_action( 'phpmailer_init', 'wpse_224496_phpmailer_init' );

    // Example: only SMTP for subject "Foo"
    if ( $mail['subject'] === 'Foo' )
        add_action( 'phpmailer_init', 'wpse_224496_phpmailer_init' );

    // Other properties
    $mail['message'];
    $mail['headers']; // Could be string or array
    $mail['attachments']; // Could be string or array

    return $mail;
}

add_filter( 'wp_mail', 'wpse_224496_wp_mail' );
  • Your code pointed me in the right direction, thank you. I also had to add a foreach loop for the $headers array, searching for a match via strpos, as my SMTP condition depends on the "From" email address. – tomyam Apr 22 '16 at 12:54
  • Then you should give code here. Otherwise your answer should be removed and added as a comment to the relevant answer – Phill Healey May 4 '17 at 23:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.