From 62a11e258a1d044838de082f11b385bae6ed20e8 Mon Sep 17 00:00:00 2001 From: abnercoimbre Date: Wed, 20 Sep 2023 12:21:07 -0700 Subject: [PATCH] Split mailing list into chunks of 500 emails to respect Postmark's API limits. Thanks Asaf for pointing this out --- send_mail.py | 52 +++++++++++++++++++++++++++++++--------------------- 1 file changed, 31 insertions(+), 21 deletions(-) diff --git a/send_mail.py b/send_mail.py index b5029fb..ddb2cf5 100644 --- a/send_mail.py +++ b/send_mail.py @@ -5,6 +5,7 @@ # ============================ Contributors ========================= # Bug & warning fixes # Jacob Bell (@MysteriousJ) +# Asaf Gartner # # Emotional Support # Cucui Ganon Rosario @@ -68,30 +69,39 @@ def sendPostmarkMessage(subject, body, to): } messages = [] - for email in to: - message = { - "From": POSTMARK_SENDER_EMAIL, - "To": email, - "TemplateId": POSTMARK_TEMPLATE_ID, - "TemplateModel": { - "name": SENDER_NAME, - "email": POSTMARK_SENDER_EMAIL, - "body": body, - "subject": subject - }, - "MessageStream": POSTMARK_MESSAGE_STREAM + + # Postmark supports 500 messages per API call. + # Split the 'to' list into chunks of 500 or fewer email addresses + for i in range(0, len(to), 500): + to_chunk = to[i:i+500] + + for email in to_chunk: + message = { + "From": POSTMARK_SENDER_EMAIL, + "To": email, + "TemplateId": POSTMARK_TEMPLATE_ID, + "TemplateModel": { + "name": SENDER_NAME, + "email": POSTMARK_SENDER_EMAIL, + "body": body, + "subject": subject + }, + "MessageStream": POSTMARK_MESSAGE_STREAM + } + messages.append(message) + + payload = { + "Messages": messages } - messages.append(message) - payload = { - "Messages": messages - } + # Debug: + # print(json.dumps(payload, indent=4)) - # Debug: - # print(json.dumps(payload, indent=4)) - - result = requests.post(POSTMARK_API_URL, headers=headers, json=payload) - print(result.text) + result = requests.post(POSTMARK_API_URL, headers=headers, json=payload) + print(result.text) + + # Clear the messages list for the next chunk + messages.clear() if __name__ == '__main__': # Create a ConfigParser object and read the INI file