flask-mail
flask-mail copied to clipboard
JSON serialization
Not entirely sure what you can do about this but when using w/ Celery
and the task serializer is set to json
it blows up. Won't even send a base flask mail object.
kombu.exceptions.EncodeError: <flask_mail.Attachment object at 0x2b32810> is not JSON serializable
Had to do an ugly work around
# helpers.py
def send_template_email(subject, recipients, template_name, context, attachments=None):
'''
Sends async email with templates and optional attachments
:param subject: Email subject.
:param recipients: List of recipients.
:param template_name: Name of template. Should be in templates/emails
:param context: Template context variables
:param attachments: List of dictionaries that describes attachments
attachments = [
{
'type': 'csv',
'loc': absolute path,
'file_name': file name
}
]
:return: None
'''
with app.app_context():
html = render_template('/emails/{}.html'.format(template_name), **context)
text = render_template('/emails/{}.txt'.format(template_name), **context)
msg = Message(
subject=subject,
recipients=recipients,
body=text,
html=html
)
send_email_async.delay(msg.__dict__, attachments)
# tasks.py
@celery.task
def send_email_async(data, attachments=None):
with app.app_context():
msg = Message()
msg.__dict__.update(data)
if attachments:
for a in attachments:
if a['type'] == 'csv':
csv_file = MIMEBase('application', 'octect-stream')
csv_file.set_payload(open(a['loc'], 'rb').read())
Encoders.encode_base64(csv_file)
csv_file.add_header('Content-Disposition', 'attachment', filename=a['file_name'])
msg.attach(csv_file)
mail.send(msg)