Home > Software engineering >  Flask-Email creates multiple threads when sending emails to many users in a loop
Flask-Email creates multiple threads when sending emails to many users in a loop

Time:07-26

I have a flask application. I have written a loop which goes through a database and looks for users and based on some conditions sends emails to them.

for receiver in new_receivers:
    user = User.query.filter_by(organization=receiver).first()
    send_email(subject='You have new messages!',
    sender='[email protected]',
    recipient=user.email,
    text_body= 'test',
    html_body= 'test')

Sending email creates a new thread for sending email like this:

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


def send_email(subject : str , sender : str , recipient : str , text_body='' , html_body='')->None:

    msg = Message(subject, sender=sender, recipients=[recipient])
    msg.body = text_body
    msg.html = html_body
    Thread(target=send_async_email, args=(app, msg)).start()

Is there a way to avoid creating hundreds of threads, but pass a list of emails to the thread and loop sending in here?

CodePudding user response:

I collected messeges to list and passed them to thread, where send them in a loop.

emails = []
for receiver in new_receivers:
    user = User.query.filter_by(organization=receiver).first()



    emails.append(
        {
            "subject" : 'You have new messages!',
            "sender" : '[email protected]',
            "recipient" : user.email,
            "text_body" : 'test',
            "html_body" : 'test'
        }
    )

meseges = []
for email in emails:
    msg = Message(email["subject"], sender=email["sender"], recipients=email["sender"])
    msg.body = email["text_body"]
    msg.html = email["html_body"]
    meseges.append(msg)



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


def send_messeges(messegs)->None:

    Thread(target=send_async_email, args=(app, messegs)).start()
  • Related