![图片[1]-短信验证码发送实现(详细教程)-初晴小屋](https://cdn-docs-new.pingcode.com/baike/wp-content/uploads/2024/09/5e2593fce7f2300a9212040a9ff3f5af.webp)
首先,我们需要创建一个HTML表单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Send Verification Code</title>
</head>
<body>
<form action="/send-code" method="post">
<label for="contact">Phone or Email:</label>
<input type="text" id="contact" name="contact" required>
<button type="submit">Send Code</button>
</form>
</body>
</html>
2. 服务器端处理
在服务器端,我们需要处理表单提交,生成验证码,并发送到用户的手机号或邮箱。以下是一个简单的Python Flask示
例:
import random
import smtplib
app = Flask(__name__)
@app.route('/send-code', methods=['POST'])
def send_code():
contact = request.form['contact']
code = str(random.randint(1000, 9999))
# 发送验证码到手机或邮箱
if '@' in contact:
send_email(contact, code)
else:
send_sms(contact, code)
return jsonify({'message': 'Verification code sent!'})
def send_email(to, code):
from_email = 'your_email@example.com'
password = 'your_password'
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login(from_email, password)
server.sendmail(from_email, to, f'Subject: Your verification codennYour code is {code}')
server.quit()
def send_sms(to, code):
# 使用第三方短信API发送短信
pass
if __name__ == '__main__':
app.run(debug=True)
二、利用JavaScript进行异步请求
与表单提交相比,利用JavaScript进行异步请求能带来更好的用户体验,不需要页面刷新。
1. 修改HTML表单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Send Verification Code</title>
</head>
<body>
<form id="verification-form">
<label for="contact">Phone or Email:</label>
<input type="text" id="contact" name="contact" required>
<button type="submit">Send Code</button>
</form>
<script>
document.getElementById('verification-form').addEventListener('submit', function(event) {
event.preventDefault();
var contact = document.getElementById('contact').value;
fetch('/send-code', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ contact: contact })
})
.then(response => response.json())
.then(data => alert(data.message))
.catch(error => console.error('Error:', error));
});
</script>
</body>
</html>
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END








暂无评论内容