In my WordPress v6.0, I have configured sending SMTP mails ([email protected]) through $phpmailer
which is working fine.
I want to use another SMTP email account ([email protected]) 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 = '[email protected]';
$phpmailer->Password = 'password1';
$phpmailer->SMTPSecure = 'ssl';
$phpmailer->From = '[email protected]';
$phpmailer->FromName = 'Site Contact Form';
} else {
$phpmailer->Host = 'smtp.example.com';
$phpmailer->SMTPAuth = 'true';
$phpmailer->Port = 465;
$phpmailer->Username = '[email protected]';
$phpmailer->Password = 'password2';
$phpmailer->SMTPSecure = 'ssl';
$phpmailer->From = '[email protected]';
$phpmailer->FromName = 'Site Mail';
}
}
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;
}