You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

集成Google reCAPTCHA v3的PHP邮件发送功能异常求助

解决方案

1. 替换PHP原生mail()为SMTP发送

PHP原生mail()返回true仅代表服务器接收了请求,不意味着邮件成功送达。多数虚拟主机默认未正确配置邮件服务,导致邮件被丢弃或拦截。最可靠的方案是使用SMTP库(如PHPMailer):

// 需先通过Composer安装PHPMailer或手动引入文件
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);
try {
    // SMTP服务器配置(以Gmail为例)
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'your-email@gmail.com';
    $mail->Password   = 'your-app-specific-password'; // Gmail需用应用专用密码
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $mail->Port       = 465;

    // 收件人与发件人
    $mail->setFrom($email, $name);
    $mail->addAddress($mail_to);
    $mail->addReplyTo($email, $name);

    // 邮件内容
    $mail->isHTML(false);
    $mail->Subject = $subject;
    $mail->Body    = $content;

    $mail->send();
    http_response_code(200);
    echo '<p class="alert alert-success">Thank You! Your message has been successfully sent.</p>';
} catch (Exception $e) {
    http_response_code(500);
    echo '<p class="alert alert-warning">Something went wrong, your message could not be sent.</p>';
}

2. 规范邮件头格式

原邮件头不符合RFC标准,易被反垃圾系统拦截,修改为:

$headers = "From: \"$name\" <$email>\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

3. 排查服务器邮件日志

查看服务器邮件日志(如Linux的/var/log/mail.log,虚拟主机可在控制面板查看),确认邮件被拒收的具体原因(如SPF/DKIM验证失败、被标记为垃圾邮件)。

4. 验证reCAPTCHA实际结果

取消注释print_r($response);,查看reCAPTCHA完整返回数据,确认是否存在error-codes字段,排查验证是否真的成功。

5. 测试基础邮件发送

编写极简脚本排除表单和reCAPTCHA干扰,确认服务器能否正常发信:

<?php
$to = "myemail@gmail.com";
$subject = "Test Email";
$message = "This is a test message from the server.";
$headers = "From: Test Sender <test@your-domain.com>\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

if(mail($to, $subject, $message, $headers)){
    echo "Mail sent successfully";
} else {
    echo "Mail failed to send";
}
?>

内容的提问来源于Stack Exchange,提问作者Wissam Baltaji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 05:18:20