如何通过SMTP发送HTML表单数据到Gsuite邮箱避免被拦截或入垃圾箱
修复步骤
1 前置基础修正
- 你的HTML表单添加
method="post"属性,避免参数通过URL传递,修改后代码:
<form name='form1' action="/wp-includes/phpmailer2/sendMail.php" method="post"> <input id="first_name" name="first_name" required="required" type="text" value="" placeholder="" > </form>
- 修复原有PHP代码的语法错误:你现有代码中
$first_name赋值写在PHP闭合标签外,$msg定义时未提前获取参数、末尾多了冗余拼接符,$comments变量未定义,这些问题都会导致代码运行异常。
2 改用PHPMailer走SMTP发送
AWS封禁25端口,所以使用Gmail SMTP的465(SSL)或587(TLS)端口发送,操作如下:
- 下载PHPMailer源码放到
/wp-includes/phpmailer2/目录下 - 进入Gsuite后台,开启对应发件邮箱的SMTP权限,若开启了两步验证,需要生成专属应用密码用于SMTP登录
- 替换
sendMail.php的全部代码为以下内容,替换对应配置项为你自己的实际值:
<?php // 引入PHPMailer文件 require 'PHPMailer/src/PHPMailer.php'; require 'PHPMailer/src/SMTP.php'; require 'PHPMailer/src/Exception.php'; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; // 配置项 $webmaster_email = "user@example.com"; // 收件邮箱 $sender_email = "noreply@yourdomain.com"; // 发件邮箱,必须是Gsuite下你域名的已验证邮箱 $sender_name = "你的网站名称"; $smtp_password = "你的Gsuite应用密码"; // 开启两步验证就填应用密码,没开就填邮箱密码 $feedback_page = "feedback_form.html"; $error_page = "error_message.html"; $thankyou_page = "https://rentersshield.org/success/"; // 获取表单参数 $first_name = $_REQUEST['first_name'] ?? ''; function isInjected($str) { $injections = array('(\n+)', '(\r+)', '(\t+)', '(%0A+)', '(%0D+)', '(%08+)', '(%09+)' ); $inject = join('|', $injections); $inject = "/$inject/i"; return preg_match($inject,$str); } // 参数校验 if (!isset($_REQUEST['first_name'])) { header( "Location: $feedback_page" ); exit; } elseif (empty($first_name) ) { header( "Location: $error_page" ); exit; } elseif ( isInjected($first_name) ) { header( "Location: $error_page" ); exit; } // 组装邮件内容 $msg = "First Name: " . $first_name; // SMTP发送 $mail = new PHPMailer(true); try { // 服务器配置 $mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = $sender_email; $mail->Password = $smtp_password; $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; $mail->Port = 465; // 收件人 $mail->setFrom($sender_email, $sender_name); $mail->addAddress($webmaster_email); // 内容 $mail->Subject = 'New Form Submission'; $mail->Body = $msg; $mail->send(); header( "Location: $thankyou_page" ); exit; } catch (Exception $e) { header( "Location: $error_page" ); exit; } ?>
3 配置域名DNS记录避免进入垃圾箱
这一步是确保Gsuite不拦截你邮件的核心,需要在你的域名DNS解析后台添加以下3条记录:
- SPF记录:类型为TXT,主机记录填@,值为
v=spf1 include:_spf.google.com ~all - DKIM记录:进入Gsuite后台生成DKIM密钥,添加对应TXT记录
- DMARC记录:类型为TXT,主机记录填_dmarc,值为
v=DMARC1; p=none; sp=none; rua=mailto:dmarc@你的域名,后续稳定后可以把p值改为quarantine或者reject提升安全性
4 AWS侧配置
到AWS安全组的出站规则中,放开465端口的TCP访问权限,不要使用25端口即可。
内容的提问来源于stack exchange,提问作者John Adams
相关产品推荐
相关产品推荐

