import os
from flask import current_app
from flask_babel import lazy_gettext as _
from flask_emails import Message
from xmm.models.fields import StringField
from .base import Transfer
[docs]class EmailTransfer(Transfer):
"""Send mail."""
params = [
{
'key': 'subject',
'label': _('Betreff'),
'default': '',
'datatype': StringField.type_name,
},
{
'key': 'to',
'label': _('To:'),
'default': '',
'datatype': StringField.type_name,
},
{
'key': 'cc',
'label': _('CC:'),
'default': '',
'datatype': StringField.type_name,
},
{
'key': 'bcc',
'label': _('Bcc:'),
'default': '',
'datatype': StringField.type_name,
},
{
'key': 'mail_from',
'label': _('From:'),
'default': '',
'datatype': StringField.type_name,
},
{
'key': 'body',
'label': _('Body:'),
'default': '',
'datatype': StringField.type_name,
},
]
[docs] def __init__(self, subject=None, to=None, cc=None, bcc=None, mail_from=None, body=None):
"""
Send an email report of the pipeline.
:param str subject: A subject to use, supports strftime placeholders.
:param str[] to: A list of recipients
:param str[] cc: Carbon-copy recipient list
:param str[] bcc: Blind copy recipient list
:param str mail_from: From: email address
At least one of to, cc or bcc must be set.
"""
super().__init__()
self.subject = subject
self.to = to or []
self.cc = cc or []
self.bcc = bcc or []
self.mail_from = mail_from or current_app.config.get('EMAIL_DEFAULT_SENDER')
self.body = body
self.mime_type = None
self.filepath = None
if not any([to, cc, bcc]):
raise RuntimeError('Email requires at least one recipient!')
if not self.body:
self.body = 'Datei verschickt mit automatischer E-Mail.' # message must have non-empty body
def begin(self, context=None):
self.mime_type = context['write']['mime_type']
self.filepath = context['write']['filename']
def transfer(self):
message = Message(subject=self.subject)
with open(self.filepath, 'rb') as fp:
message.attach(data=fp, filename=os.path.basename(self.filepath), mime_type=self.mime_type)
message.mail_to = self.to
message.cc = self.cc
message.bcc = self.bcc
message.mail_from = self.mail_from
message.text = self.body
message.send()