mails.py 1.47 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
import smtplib
from email.mime.text import MIMEText
from collections import defaultdict
from sys import stderr
import email.charset

# Switch to quoted-printable so that we don't get something completely
# unreadable for non-ASCII chars if we have to look at raw email
email.charset.add_charset('utf-8', email.charset.QP, email.charset.QP, 'utf-8')

Colomban Wendling's avatar
Colomban Wendling committed
11

12
def send_email_for_check(check):
13
    from . import config
14
    # ensure we do not traceback with unknown substitutions
15
    subject = config.emails.subject_tpl.format_map(
Colomban Wendling's avatar
Colomban Wendling committed
16 17 18 19
        defaultdict(lambda: "<no substitution>",
                    state='OK' if check.ok else 'Problem',
                    check=check.__class__.__name__,
                    dest=check.target_name))
20 21

    msg_text = ''
22 23 24
    if not check.ok:
        msg_text += ("Check %s failed:\n%s" %
                    (str(check), check.errmsg.strip()))
25 26 27 28 29

    # encode / decode is a fix that didn't make it into Debian Wheezy
    # http://bugs.python.org/issue16948
    msg = MIMEText(msg_text.encode('utf-8').decode('latin1'), 'plain', 'utf-8')
    msg['Subject'] = subject
30
    msg['From']    = config.emails.addr_from
31
    msg['To']      = ", ".join(config.emails.to)
32 33

    try:
34
        server = smtplib.SMTP(config.emails.smtp_host)
35
        # server.set_debuglevel(1)
Colomban Wendling's avatar
Colomban Wendling committed
36 37
        server.sendmail(config.emails.addr_from, config.emails.to,
                        msg.as_string())
38 39 40
        server.quit()
    except Exception as e:
        print("Couldn't send email: %s" % str(e), file=stderr)