BBS论坛(三十三)
2025年01月15日 02:41:40

LIKE.TG | 发现全球营销软件&服务汇聚顶尖互联网营销和AI营销产品,提供一站式出海营销解决方案。唯一官网:www.like.tg
33.celery实现邮件异步发送
(1)task.py
pip install celery redis
from celery import Celery
from flask import Flask
from flask_mail import Message
from exts import mail,alidayu
import config
app=Flask(__name__)
app.config.from_object(config)
mail.init_app(app)
alidayu.init_app(app)
# 运行本文件:
# 在windows操作系统上:
# celery -A tasks.celery worker --pool=solo --loglevel=info
# 在linux操作系统上:
# celery -A tasks.celery worker --loglevel=info
def make_celery(app):
celery = Celery(app.import_name, backend=app.config['CELERY_RESULT_BACKEND'],
broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
return celery
celery = make_celery(app)
@celery.task
def send_mail(subject,recipients,body):
message = Message(subject=subject,recipients=recipients,body=body)
mail.send(message)
# @celery.task
# def send_sms_captcha(telephone,captcha):
# alidayu.send_sms(telephone,code=captcha)
(2)config.py
# celery的配置
CELERY_RESULT_BACKEND = "redis://127.0.0.1:6379/0"
CELERY_BROKER_URL = "redis://127.0.0.1:6379/0"
(3)cms/views.py
@bp.route('/email_captcha/')
def email_captcha():
#获取要修改的邮箱
email = request.args.get('email')
if not email:
return restful.params_error('请输入要修改的邮箱')
#得到大小写字母的列表
source = list(string.ascii_letters)
#得到大小写字母的列表 + 0到9的数字字符串
source.extend(map(lambda x: str(x), range(0, 10)))
# 随机取六位作为验证码
captcha = "".join(random.sample(source, 6))
#给这个邮箱发送邮件验证码
# message = Message(subject='derek论坛密码修改邮件发送', recipients=[email,], body='你的验证码是:%s'%captcha)
# try:
# mail.send(message)
# except:
# return restful.server_error()
#celery异步发送邮件
send_mail.delay('derek论坛密码修改邮件发送', [email], '你的验证码是:%s' % captcha)
#把邮箱和验证码保存到memcached中
zlcache.set(email,captcha)
return restful.success()

LIKE.TG:汇集全球营销软件&服务,助力出海企业营销增长。提供最新的“私域营销获客”“跨境电商”“全球客服”“金融支持”“web3”等一手资讯新闻。
点击【联系客服】 🎁 免费领 1G 住宅代理IP/proxy, 即刻体验 WhatsApp、LINE、Telegram、Twitter、ZALO、Instagram、signal等获客系统,社媒账号购买 & 粉丝引流自助服务或关注【LIKE.TG出海指南频道】、【LIKE.TG生态链-全球资源互联社区】连接全球出海营销资源。
本文由LIKE.TG编辑部转载自互联网并编辑,如有侵权影响,请联系官方客服,将为您妥善处理。
This article is republished from public internet and edited by the LIKE.TG editorial department. If there is any infringement, please contact our official customer service for proper handling.
Server deployment全球论坛人工智能论坛全球峰会发展论坛战略论坛开放论坛程序员论坛互联网峰会科技峰会