首页  >  问答  >  正文

如何根据特定条件在PHPMailer中选择SMTP帐户?

在我的 WordPress v6.0 中,我配置了通过 $phpmailer 发送 SMTP 邮件 (no-reply@example.com),工作正常。

我想使用另一个 SMTP 电子邮件帐户 (contact@example.com) 进行所有自定义联系表单通信。

使用 wp_mail() 发送联系表单电子邮件,如下所示:

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

如何识别上述 wp_mail 并使用特定的 SMTP 帐户?下面是我的代码,没有真正的 if 条件来检查:

// 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粉315680565P粉315680565232 天前588

全部回复(1)我来回复

  • P粉135799949

    P粉1357999492024-02-05 09:12:30

    这就是我解决这个问题的方法。

    在评论表单电子邮件中包含自定义标头:评论:评论表单

    使用wp_mail过滤器,检查评论表单发送的电子邮件是否如下:

    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;
    }

    回复
    0
  • 取消回复