1from smtplib import SMTP
2
3
4def sendmail(config, message):
5    port = config['MAIL'].get('port', 587)
6    ssl = config['MAIL'].get('ssl', True)
7    host = config['MAIL'].get('host', None)
8    username = config['MAIL'].get('username', None)
9    password = config['MAIL'].get('password', None)
10    if None not in [host, username, password]:
11        server = SMTP(host=host, port=port)
12        if ssl:
13            server.ehlo()
14            server.starttls()
15            server.ehlo()
16        server.login(username, password)
17        to = message.get('To', [])
18        bcc = message.get('Bcc', [])
19        if not isinstance(to, list):
20            to = [to]
21        if not isinstance(bcc, list):
22            bcc = [bcc]
23        to += bcc
24        server.sendmail(
25            message['From'],
26            to,
27            message.as_string().encode('utf-8')
28        )
29