From e9af13c9d880c3d3c047aa444e036bf3eb5855ac Mon Sep 17 00:00:00 2001 From: flavis Date: Thu, 13 Jan 2022 12:12:36 +0100 Subject: [PATCH] fix using too many connections --- jdav_web/jdav_web/settings.py | 7 +++++++ jdav_web/mailer/mailutils.py | 36 ++++++++++++++++++++--------------- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/jdav_web/jdav_web/settings.py b/jdav_web/jdav_web/settings.py index c67fa34..b1d0fbc 100644 --- a/jdav_web/jdav_web/settings.py +++ b/jdav_web/jdav_web/settings.py @@ -176,6 +176,13 @@ EMAIL_USE_TLS = True if deployed else False EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend' +# Celery Email Setup + +CELERY_EMAIL_TASK_CONFIG = { + 'rate_limit' : '1/m' # * CELERY_EMAIL_CHUNK_SIZE (default: 10) +} + + # Admin setup ADMINS = (('admin', 'christian@merten-moser.de'),) diff --git a/jdav_web/mailer/mailutils.py b/jdav_web/mailer/mailutils.py index c993bf3..424cb4c 100644 --- a/jdav_web/mailer/mailutils.py +++ b/jdav_web/mailer/mailutils.py @@ -20,21 +20,27 @@ def send(subject, content, sender, recipients, message_id=None, reply_to=None, headers = {'Message-ID': message_id} else: headers = {} - with mail.get_connection() as connection: - for recipient in set(recipients): - email = EmailMessage(subject, content, sender, [recipient], - headers=headers, - connection=connection, **kwargs) - if attachments is not None: - for attach in attachments: - email.attach_file(attach) - try: - email.send(fail_silently=True) - except Exception as e: - print("Error when sending mail:", e) - failed = True - else: - succeeded = True + + # construct mails + mails = [] + for recipient in set(recipients): + email = EmailMessage(subject, content, sender, [recipient], + headers=headers, **kwargs) + if attachments is not None: + for attach in attachments: + email.attach_file(attach) + mails.append(email) + try: + # connect to smtp server + connection = mail.get_connection() + # send all mails with one connection + connection.send_messages(mails) + except Exception as e: + print("Error when sending mail:", e) + failed = True + else: + succeeded = True + return NOT_SENT if failed and not succeeded else SENT if not failed\ and succeeded else PARTLY_SENT