十三、Python——随机生成验证码至邮箱

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)


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值