Flask邮件,正在发送重复邮件

2024-05-02 01:23:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python和Flask Mail。我试图在用户确认其帐户后发送欢迎电子邮件,方法是单击之前作为电子邮件发送给用户以确认其帐户的链接。在通过将数据库中已确认条目的值更改为true来确认他的帐户后,我发送了欢迎电子邮件。但它发送了5封重复的电子邮件,而不是一封

我使用了以下代码-

class AccountConfirmation(Resource):
    @jwt_required    
    def post(self):
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        user.confirmed = True
        db.session.commit()
        send_welcome_email(user)
        return {'msg': 'Account confirmed successfully. You can now login to your account'}, 200 

def send_welcome_email(user):
    subject = '...'
    body = '...'
    sender = Config.ADMINS[0]
    recipients = [user.email_id]
    send_email(subject, body, sender, recipients)

from flask_mail import Message
def send_email(subject, body, sender, recipients):
    msg = Message(subject = subject, body = body, sender=sender, recipients=recipients)
    mail.send(msg)

Tags: 用户sendid电子邮件emaildefbodymsg
1条回答
网友
1楼 · 发布于 2024-05-02 01:23:30

我没有发现代码有任何问题。除非有多个发送邮件的请求。要克服它,您可以尝试发送异步电子邮件。请检查这段代码,不要忘记检查link以获得更好的解释

from threading import Thread
# ...

def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)


def send_email(subject, sender, recipients, text_body, html_body):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    Thread(target=send_async_email, args=(app, msg)).start()

相关问题 更多 >