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

如何为HTML模态框实现PHP提交姓名/邮箱/消息功能?

替代SMTPJS的PHP邮件发送方案(适配HostGator主机)

核心方案说明

HostGator不支持SMTP直连,可直接在现有HTML文件中内嵌PHP代码处理邮件发送(无需单独创建index.php),若主机不允许HTML文件解析PHP,只需将index.html重命名为index.php即可,原有HTML内容不受影响。


完整替换代码

1. 顶部内嵌PHP处理逻辑

在index.html文件最顶部添加以下代码(置于所有HTML内容之前):

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // 获取表单提交数据
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $message = trim($_POST['message']);
    
    // 替换为你的收件邮箱
    $to = 'main-account@gmail.com';
    $subject = "New Connection";
    
    // 邮件内容格式
    $body = "Name: $name<br>Email: $email<br>Message: $message";
    
    // 设置HTML格式邮件头
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: <$email>" . "\r\n";
    
    // 调用HostGator自带mail函数发送邮件
    $sendResult = mail($to, $subject, $body, $headers);
    
    // 发送结果提示
    if ($sendResult) {
        echo "<script>alert('消息发送成功!');</script>";
    } else {
        echo "<script>alert('发送失败,请稍后重试!');</script>";
    }
}
?>

2. 修改表单及交互逻辑

替换原有SMTPJS脚本和表单触发逻辑为以下内容:

<!-- 模态框内的表单(更新form属性) -->
<form id="contactForm" method="POST">
    <input type="text" id="name" name="name" placeholder="NAME" required>
    <input type="email" id="email" name="email" placeholder="EMAIL" required>
    <textarea id="message" name="message" placeholder="MESSAGE" required></textarea>
    <button type="submit">SEND</button>
</form>

<!-- 可选:无刷新提交脚本(避免页面跳转) -->
<script>
document.getElementById('contactForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    
    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
    .then(() => {
        alert('消息发送成功!');
        this.reset();
    })
    .catch(() => {
        alert('发送失败,请稍后重试!');
    });
});
</script>

注意事项

  • 确保表单输入框都添加了name属性,需与PHP中$_POST的参数名对应,否则无法获取提交数据。
  • HostGator的mail()函数发送的邮件可能被归类为垃圾邮件,建议在收件邮箱中将你的域名加入白名单。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:25:40