In my WordPress v6.0, I configured sending SMTP mail (no-reply@example.com) via $phpmailer
and it works fine.
I want to use another SMTP email account (contact@example.com) for all custom contact form communications.
Send a contact form email using wp_mail()
like this:
wp_mail($form_to, $form_subject, $form_body, implode("\r\n", $form_headers));
How to identify the above wp_mail
and use a specific SMTP account? Below is my code, 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'; } }
P粉1357999492024-02-05 09:12:30
This is how I solved this problem.
Include custom headers in your comment form emails: Comments: Comment Form
.
Use the wp_mail
filter to check if the email sent by the comment form is as follows:
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; }