邮箱发送验证码功能

jiaqilin_branch
HAPE 4 months ago
parent 44504b52e7
commit 4b5aa177bb

@ -1,2 +0,0 @@
# double_program

@ -0,0 +1,7 @@
# double_program
### 发送验证码邮件功能模块
使用126邮箱发送

@ -0,0 +1,58 @@
import smtplib
import random
import re
from email.mime.text import MIMEText
def is_valid_email(email):
# 简单邮箱格式校验
return re.match(r"[^@]+@[^@]+\.[^@]+", email)
def send_verification_code(email, code):
smtp_server = 'smtp.126.com'
smtp_port = 25
sender_email = 'hape233@126.com'
sender_password = 'ZKcbV37TdRwgnsZC'
msg = MIMEText(f'您的验证码是:{code}')
msg['Subject'] = '登录验证码'
msg['From'] = sender_email
msg['To'] = email
try:
server = smtplib.SMTP(smtp_server, smtp_port, timeout=30)
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, [email], msg.as_string())
print("邮件发送成功")
return True
except Exception as e:
print(f"邮件发送失败:{e}")
return False
finally:
try:
server.quit()
except:
server.close()
def main():
email = input("请输入您的邮箱:")
if not is_valid_email(email):
print("邮箱格式不正确!")
return
code = str(random.randint(100000, 999999))
try:
send_verification_code(email, code)
print("验证码已发送,请查收邮箱。")
except Exception as e:
print("验证码发送失败:", e)
return
user_code = input("请输入收到的验证码:")
if user_code == code:
print("登录成功!")
else:
print("验证码错误,登录失败。")
if __name__ == "__main__":
main()
Loading…
Cancel
Save