Created
October 11, 2022 18:45
-
-
Save augustomen/8bfb256d0fef68cf99dd812a50feaa10 to your computer and use it in GitHub Desktop.
Flask-Mailman backend to send emails via AWS SES
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Flask-Mailman backend to send emails via AWS SES.""" | |
import boto3 | |
from botocore.exceptions import ClientError | |
from flask_mailman.backends.base import BaseEmailBackend | |
class EmailBackend(BaseEmailBackend): | |
"""Implements sending email via SES through boto3. | |
Usage (in settings): | |
MAIL_BACKEND = 'flask_mailman_ses.EmailBackend' | |
""" | |
def __init__(self, *args, **kwargs): | |
super().__init__(*args, **kwargs) | |
self.client = boto3.client('ses') | |
def send_messages(self, email_messages): | |
"""Send one or more EmailMessage objects and return the number of email messages sent.""" | |
if not email_messages: | |
return 0 | |
num_sent = 0 | |
for message in email_messages: | |
num_sent += self._send(message) | |
return num_sent | |
def _send(self, message): | |
"""Sends a single instance of flask_mailman.EmailMessage.""" | |
try: | |
email_message = message.message() | |
response = self.client.send_raw_email( | |
Source=email_message['From'], | |
Destinations=message.recipients(), | |
RawMessage={'Data': email_message.as_string()}, | |
) | |
return 1 if response.get('MessageId') else 0 | |
except ClientError: | |
if self.fail_silently: | |
return 0 | |
raise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment