非本地环境下使用PHP mail()函数发送邮件失败问题求助
问题排查与修复方案
1. PHP源码直接暴露的问题
PHP是服务端脚本语言,必须运行在搭载PHP解析引擎的Web服务环境中才能执行,你当前没有搭建本地服务器,直接通过本地文件路径打开站点,浏览器会将PHP文件识别为普通文本直接输出,不会执行任何代码逻辑。
解决方法:Windows平台安装XAMPP、WAMP等集成Web环境,将项目代码放入环境的站点根目录,通过http://localhost/项目路径的形式访问站点,PHP代码才会被正常解析执行。
2. 表单提交逻辑错误
你的提交按钮外层嵌套了<a href="arigato.html">标签,点击按钮时会优先触发a标签的跳转,不会触发form表单的POST提交逻辑,PHP完全接收不到表单提交的参数。
解决方法:删除按钮外层的a标签,提交成功后的跳转逻辑放在PHP侧处理即可。
3. mail()函数无法发信的问题
Windows系统默认没有配置sendmail组件,原生mail()函数无法直接调用发信服务;同时Gmail早已禁止无身份验证的第三方发信,即使在Linux环境下直接用mail()函数发信,也会被Gmail拒收或直接归入垃圾箱。
解决方法:
- 本地调试阶段可以安装邮件测试工具校验发信逻辑
- 线上环境建议使用PHPMailer等类库,通过Gmail的SMTP服务进行身份验证后发信,需要提前开启Gmail的应用密码功能。
修改后代码参考
submit.html 表单部分
<form class="part" action="contactform.php" method="post"> <br> <div class="input-wrapper"> <input type="text" name="UName1" placeholder="Mon nom"> </div> <br><br> <div class="input-wrapper"> <input type="text" name="UName2" placeholder="Le titre de mes notes"> </div> <br><br> <button type="submit" name="btn-send" class="input-wrapper2">J'envoie!</button> </form>
contactform.php
<?php if(isset($_POST['btn-send'])) { $UserName = trim($_POST['UName1']); $UserAccount = trim($_POST['UName2']); if(empty($UserName) || empty($UserAccount)) { header('Location: submit.html?error'); exit; } $to = "santoshpassoubady@gmail.com"; // 补充发件人 headers 避免被判定为垃圾邮件 $headers = "From: contact@yourdomain.com\r\n"; $headers .= "Content-Type: text/plain; charset=utf-8\r\n"; if(mail($to, $UserName, $UserAccount, $headers)) { // 发信成功跳转到感谢页 header("Location: arigato.html"); exit; }else{ header("Location: submit.html?send_error"); exit; } } else { header("Location: submit.html"); exit; } ?>
内容的提问来源于stack exchange,提问作者user13019482
相关产品推荐
相关产品推荐

