使用HTML/CSS/JS创建的响应式表单无法发送邮件至Gmail求助
表单邮件发送失败问题排查与修复
问题根源及修复点:
- DOM元素ID拼写错误:代码中获取邮箱值时误写为
document.getElementById("eamil"),正确ID是email,拼写错误会导致无法读取用户输入的邮箱地址,中断邮件发送逻辑。 - Gmail SMTP验证限制:Gmail目前禁止直接使用账户密码通过第三方SMTP服务发送邮件,需开启两步验证后生成应用专用密码替代原密码;或者更换为支持普通密码验证的SMTP服务商(如Outlook)。
- 表单重置时机错误:原代码在
onsubmit中先执行sendEmail()再调用reset(),但sendEmail()是异步操作,重置会提前清空表单数据,导致邮件内容获取失败,需将重置操作移至邮件发送成功的回调函数内。 - viewport语法错误:meta标签中
width-device-width应为width=device-width,缺少等号会导致响应式布局失效。 - 拼写小错误:邮件主题里的
Equiry应为Enquiry,属于细节修正。
修复后的完整代码:
<!doctype html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>codeG</title> <link rel="stylesheet" href="Style.css"> </head> <body> <div class="container"> <form onsubmit="sendEmail(); return false;"> <h3> LOGIN FORM <hr width="50px" style="background: #555; height:5px"></h3> <input type="text" id="name" placeholder="Full Name" required> <input type="email" id="email" placeholder="Valid Email" required> <input type="text" id="phone" placeholder="Valid Phone no." required> <textarea id="message" rows="4" placeholder="Leave a comment..."></textarea> <button type="Submit"> Submit </button> </form> </div> <script src="https://smtpjs.com/v3/smtp.js"> </script> <script> function sendEmail(){ Email.send({ Host : "smtp.gmail.com", Username : "ayushbharti.official123@gmail.com", Password : "你的应用专用密码", // 替换为Gmail应用专用密码 To : 'ayushbharti.official123@gmail.com', From : document.getElementById("email").value, Subject : "New Contact Form Enquiry", Body : "Name: " + document.getElementById("name").value + "<br> Email:" + document.getElementById("email").value + "<br> Phone no.:" + document.getElementById("phone").value + "<br> Message:" + document.getElementById("message").value }).then( message => { alert("Message Sent Successfully"); document.querySelector('form').reset(); // 发送成功后再重置表单 } ); } </script> </body> </html>
额外说明:
- 若使用Gmail的应用专用密码,需先在Google账户中开启两步验证,然后在「安全」设置里生成对应应用的专用密码。
内容的提问来源于stack exchange,提问作者Ayush Bharti
相关产品推荐
相关产品推荐

