flask 使用celery发送邮件详细代码
时间: 2024-05-18 10:17:21 浏览: 145
django+celery异步发送邮件
好的,下面是使用 Flask 和 Celery 发送邮件的详细代码:
1. 安装所需库
```
pip install flask flask-mail celery
```
2. 创建 Flask 应用
```
from flask import Flask
from flask_mail import Mail
app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.gmail.com' # 邮箱服务器
app.config['MAIL_PORT'] = 465 # 端口号
app.config['MAIL_USE_SSL'] = True # 是否使用 SSL
app.config['MAIL_USERNAME'] = 'your-email@gmail.com' # 发送邮件的邮箱地址
app.config['MAIL_PASSWORD'] = 'your-email-password' # 发送邮件的邮箱密码
mail = Mail(app)
@app.route('/')
def index():
return 'Hello, World!'
```
3. 创建 Celery 应用
```
from celery import Celery
celery = Celery(app.name, broker='redis://localhost:6379/0')
celery.conf.update(
CELERY_TASK_SERIALIZER='json',
CELERY_ACCEPT_CONTENT=['json'],
CELERY_RESULT_SERIALIZER='json'
)
```
4. 创建邮件发送任务
```
from flask_mail import Message
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
@celery.task(name='send_email')
def send_email(to, subject, body):
with app.app_context():
try:
msg = Message(subject=subject, recipients=[to])
msg.body = body
mail.send(msg)
logger.info(f"Email sent to {to} with subject '{subject}'")
except Exception as e:
logger.error(f"Error sending email to {to}: {e}")
```
5. 在视图函数中调用任务
```
@app.route('/send_email')
def send_email_view():
to = 'recipient-email@example.com'
subject = 'Test Email'
body = 'This is a test email sent from Flask using Celery and Flask-Mail.'
send_email.delay(to, subject, body)
return 'Email sent!'
```
以上就是使用 Flask 和 Celery 发送邮件的详细代码。注意,这里使用 Redis 作为 Celery 的消息代理,你需要安装并启动 Redis 服务。另外,为了保证邮件发送的安全性,建议把配置文件中的邮箱地址和密码存储在环境变量中,而不是明文写在代码中。
阅读全文