import random
import smtplib
import string
from email.mime.text import MIMEText
send_by = "发送方@qq.com"
password = "xkdijaeqsymoedhi"
mail_host = "smtp.qq.com" #第三方服务地址
port = 465
"""
随机产生4位验证码
"""
def code(n = 4):
s = ""
for i in range(n):
number = random.randint(0,9)
upper_alpha = chr(random.randint(65,90))
lower_alpha = chr(random.randint(90,122))
char = random.choice([number,upper_alpha,lower_alpha])
s += str(char)
return s
"""
发送消息的函数
"""
def send_email(send_to,content,subject = '验证码'):
message = MIMEText(content,'plain','utf-8')
message['From'] = send_by
message['To'] = send_to
message['Subject'] = subject
#使用第三方服务发送
smtp = smtplib.SMTP_SSL(mail_host,port,'utf-8')
smtp.login(send_by,password)
smtp.sendmail(send_by,send_to,message.as_string())
print("发送成功!!")
print(content)
def send_email_code(send_to):
verificate_code = code()
content = str("【验证码】您的验证码是:")+ verificate_code + ".如非本人操作,请忽略本条信息。"
try:
send_email(send_to=send_to,content = content)
return verificate_code
except Exception as error:
print("发送验证码失败;",error)
return False
if __name__ == '__main__':
#print(code(4))
send_to = '接收方@qq.com'
verificate_code = send_email_code(send_to = send_to)
print(verificate_code)
十三、Python——随机生成验证码至邮箱
最新推荐文章于 2024-09-15 22:31:42 发布