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

如何用PHPMailer实现HTML+JS联系表单的邮件发送功能

实现无跳转表单邮件发送(基于PHPMailer)

一、前端表单基础调整

  • 给表单添加唯一id(比如contact-form),移除表单的action和method属性(通过AJAX提交,避免页面跳转)
  • 确保所有需要提交的输入框都设置name属性(PHP靠这个获取字段值,和你现有JS验证里的ID对应即可)
  • 保留你原有的JS验证逻辑,仅在验证通过后触发AJAX提交

示例适配结构(贴合你的现有代码):

<form id="contact-form">
  <input type="text" id="name" name="name" placeholder="你的姓名">
  <input type="email" id="email" name="email" placeholder="你的邮箱">
  <textarea id="message" name="message" placeholder="留言内容"></textarea>
  <button type="submit">发送消息</button>
  <div id="form-feedback"></div> <!-- 用于显示发送结果提示 -->
</form>

二、JS验证+AJAX提交逻辑修改

保留你原有的前端验证代码,在验证通过后加入AJAX请求:

document.getElementById('contact-form').addEventListener('submit', function(e) {
  e.preventDefault(); // 阻止表单默认跳转行为

  // 这里放入你原有的前端验证逻辑,示例:
  let isValid = true;
  const name = document.getElementById('name').value.trim();
  const email = document.getElementById('email').value.trim();
  const message = document.getElementById('message').value.trim();

  if (!name) {
    isValid = false;
    alert('请填写姓名');
  }
  if (!/^\S+@\S+\.\S+$/.test(email)) {
    isValid = false;
    alert('请输入有效邮箱');
  }
  // 其他验证规则...

  if (isValid) {
    // 验证通过,发送AJAX请求到PHP脚本
    fetch('send-mail.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: `name=${encodeURIComponent(name)}&email=${encodeURIComponent(email)}&message=${encodeURIComponent(message)}`
    })
    .then(response => response.text())
    .then(data => {
      document.getElementById('form-feedback').textContent = data;
      // 发送成功后可重置表单
      if (data.includes('成功')) {
        document.getElementById('contact-form').reset();
      }
    })
    .catch(() => {
      document.getElementById('form-feedback').textContent = '发送失败,请稍后重试';
    });
  }
});

三、PHPMailer脚本调整(send-mail.php)

用你之前能正常运行的PHPMailer基础脚本,修改为接收POST参数的版本,注意字段名和表单name完全匹配:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// 引入PHPMailer文件(根据你主机上的实际路径调整)
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

// 接收POST参数,添加默认值避免报错
$name = $_POST['name'] ?? '';
$email = $_POST['email'] ?? '';
$message = $_POST['message'] ?? '';

// 后端基础验证,防止空提交
if (empty($name) || empty($email) || empty($message)) {
  echo '请填写完整的留言信息';
  exit;
}

$mail = new PHPMailer(true);

try {
  // 服务器配置(沿用你之前测试通过的配置)
  $mail->isSMTP();
  $mail->Host = 'smtp.your-email.com'; // 你的SMTP服务器地址
  $mail->SMTPAuth = true;
  $mail->Username = 'your-sender-email@xxx.com'; // 发件邮箱账号
  $mail->Password = 'your-email-password-or-auth-code'; // 邮箱密码/授权码
  $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
  $mail->Port = 465;

  // 收件人设置
  $mail->setFrom('your-sender-email@xxx.com', '网站联系表单');
  $mail->addAddress('your-receive-email@xxx.com'); // 你的目标收件邮箱

  // 邮件内容
  $mail->isHTML(true);
  $mail->Subject = '新留言:' . $name;
  $mail->Body    = "姓名:{$name}<br>邮箱:{$email}<br>留言内容:<br>{$message}";
  $mail->AltBody = "姓名:{$name}\n邮箱:{$email}\n留言内容:\n{$message}";

  $mail->send();
  echo '邮件发送成功,我们会尽快回复你';
} catch (Exception $e) {
  echo '发送失败:' . $mail->ErrorInfo;
}
?>

四、整合问题排查关键点

  • 确认PHPMailer的文件路径正确,避免相对路径错误导致脚本无法加载
  • 表单的name属性必须和PHP中$_POST的键完全一致(比如表单name="user-name",PHP就要用$_POST['user-name'])
  • 临时开启PHP错误提示,在send-mail.php开头添加:error_reporting(E_ALL); ini_set('display_errors', 1);,可查看具体报错信息
  • 检查主机是否限制了SMTP端口(比如465/587),确保端口可正常访问

内容的提问来源于stack exchange,提问作者Dhara Castilho

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:02:42