通过smtplib和email发送验证码到电子邮箱(Python3.7.X)

使用前需要在发送方的邮箱里开启POP3/SMTP服务,这里以QQ邮箱为例,设置——账户——开启服务——获得授权码,以下案例模拟发送一串纯文本的6位数字验证码,比较简单易懂,可在此基础上再完善。

效果演示:
在这里插入图片描述
代码展示:

# coding=utf-8
import smtplib
import string
import random
from email.mime.text import MIMEText

msg_from = '此处填写开启SMTP服务的邮箱'  # 发送方邮箱
passwd = '此处填写自己的授权码'  # 就是上面的授权码
to_mail = input("请输入要发送的邮箱地址:")
to = [to_mail] 
# 设置邮件内容
num = string.digits

def update_num():
    num_digits = ""
    for i in range(6):
        num1 = random.choice(num)
        num_digits = num_digits + num1

    return num_digits


content = "验证码: " + "<font color='orange' size='5px'><b>" + update_num() + "</b></font>"
# 把内容加进去
msg = MIMEText(content, 'html', 'utf-8')
# 设置邮件主题
msg['Subject'] = "邮箱验证"
# 发送方信息
msg['From'] = msg_from
# 开始发送
# 通过SSL方式发送,服务器地址和端口
try:
    s = smtplib.SMTP_SSL("smtp.qq.com", 465)
    # 登录邮箱
    s.login(msg_from, passwd)
    # 开始发送
    s.sendmail(msg_from, to, msg.as_string())
    s.quit()
    print("邮件发送成功")

except Exception as e:
    print(e)

不足之处:
1、验证码发送后没有验证过期的时间
2、没有对输入的邮箱有效性的验证判断

猜你喜欢

转载自blog.csdn.net/weixin_51424938/article/details/112399316