Wednesday, July 6, 2022

[FIXED] How to choose between SMTP accounts in PHPMailer based on certain conditions?

Issue

In my WordPress v6.0, I have configured sending SMTP mails (no-reply@example.com) through $phpmailer which is working fine.

I want to use another SMTP email account (contact@example.com) for all custom contact forms communications.

Sending contact form emails with wp_mail() as below:

 wp_mail($form_to, $form_subject, $form_body, implode("\r\n", $form_headers));

How can I identify the above wp_mail and use particular SMTP account? Below is the code I have, without the real if condition to check:

// MAILER
add_action('phpmailer_init', 'send_smtp_email', 10, 1);

function send_smtp_email($phpmailer) {

    $phpmailer->isSMTP();
    $phpmailer->isHTML(true);

    if (wp_mail == "contact_form") { // not a real condition, this is what I want to achieve
        $phpmailer->Host = 'smtp.example.com';
        $phpmailer->SMTPAuth = 'true';
        $phpmailer->Port = 465;
        $phpmailer->Username = 'contact@example.com';
        $phpmailer->Password = 'password1';
        $phpmailer->SMTPSecure = 'ssl';
        $phpmailer->From = 'contact@example.com';
        $phpmailer->FromName = 'Site Contact Form';
    } else {
        $phpmailer->Host = 'smtp.example.com';
        $phpmailer->SMTPAuth = 'true';
        $phpmailer->Port = 465;
        $phpmailer->Username = 'no-reply@example.com';
        $phpmailer->Password = 'password2';
        $phpmailer->SMTPSecure = 'ssl';
        $phpmailer->From = 'no-reply@example.com';
        $phpmailer->FromName = 'Site Mail';
    }
}

Solution

This is how I have solved this.

Included a custom header in the comment form emails: Comments: Comment Form.

Using wp_mail filters, check if the email sent by comment form as below:

add_filter('wp_mail', 'set_smtp_email_accounts');

function set_smtp_email_accounts($mail) {

    // Comment form mails custom header
    $header = $mail['headers'];
    $header_text = 'Comments: Comment Form';
    $header_check = in_array($header_text, $header);

    //if comment form mails 
    if ($header_check) {
        add_action('phpmailer_init', 'send_smtp_email_comments', 10, 1); // if comments form mail
    } else {
        add_action('phpmailer_init', 'send_smtp_email', 10, 1); 
    }

    return $mail;
}


Answered By - theKing
Answer Checked By - David Marino (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.