python发送邮件方式,结合redis

1、python原版

import smtplib
from email.mime.text import MIMEText
import random
from datetime import datetime,timedelta


def email_code_length(length):
    source = '1234567890qwertyuiopasdfghjklzxcvbnm'
    code = ''
    for i in range(length):
        code += random.choice(source)
    return code


EMAIL_HOST = 'smtp.163.com'
EMAIL_HOST_USER = 'cgq19951015@163.com'
EMAIL_HOST_PASSWORD = 'WBHUIUHLNAXRBFGH'
EMAIL_FROM = EMAIL_HOST_USER


def sendmail(email, code_type):
    
    if code_type == 1:

        code = email_code_length(6)
        #可以自定义邮件页面
        content = open('static/html/register.html', mode='r', encoding='utf-8').read()

        msg=MIMEText(content,"html","utf-8")
        msg['Subject']= '欢迎注册管理系统,你的验证码是:  ' + code
        msg['From']= EMAIL_FROM
        msg['To']= email

        try:

            server=smtplib.SMTP()
            server.connect(EMAIL_HOST)
            server.login(EMAIL_HOST_USER,EMAIL_HOST_PASSWORD)
            server.sendmail(EMAIL_FROM, email, msg.as_string())
            server.close()
            
			#设置过期时间,可以利用redis来做
            actime  = datetime.now() + timedelta(minutes=5)
            return (code, code_type, actime)

        except Exception as e:
            print (e)
            return False

2、改良版(结合redis)

import json
from redis import Redis
conn = Redis(host='127.0.0.1', port=6379)

ps = conn.pubsub()
ps.subscribe('email')
while True:    
    for obj in ps.listen():        
        if obj.get('type', None) == 'message':            
            params = obj.get('data', None)            
            ret = json.loads(params)            
            sendmail(ret[0], ret[1])
            
#上面代码加在上面的代码框后;下面的代码加在需要发送邮件的位置
import json
from redis import Redis
conn = Redis(host='127.0.0.1', port=6379)
conn.publish('email', json.dumps((email, 1)))
posted @ 2021-03-15 11:27  ChenXiDylan  阅读(54)  评论(0)    收藏  举报