diff options
author | Jon Turney <jon.turney@dronecode.org.uk> | 2023-07-08 15:23:11 +0300 |
---|---|---|
committer | Jon Turney <jon.turney@dronecode.org.uk> | 2023-08-15 17:57:00 +0300 |
commit | 3d778791f91c1440fb6a5a7418d9549071ee7814 (patch) | |
tree | 6b0eea036e41617610cbe28b7d121a7742b75b0d /calm/utils.py | |
parent | f2764f165b23b2e9ae03849c84fb7ed310ed12b7 (diff) |
Factor out email sending to utils
Smooth out some issues when --email isn't specified, making args.email
an empty list rather than None, which can't be iterated.
When the To: address is 'debug', dump email to log, rather than stdout.
Diffstat (limited to 'calm/utils.py')
-rw-r--r-- | calm/utils.py | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/calm/utils.py b/calm/utils.py index 9f75813..47085fd 100644 --- a/calm/utils.py +++ b/calm/utils.py @@ -25,6 +25,8 @@ # utility functions # +import email.message +import email.utils import filecmp import logging import os @@ -158,3 +160,39 @@ def mtime_cache(user_function): return result return wrapper + + +def sendmail(hdr, msg): + # sending email not enabled + if not hdr['To']: + return + + # build the email + m = email.message.Message() + + for h in hdr: + m[h] = hdr[h] + m['Message-Id'] = email.utils.make_msgid() + m['Date'] = email.utils.formatdate() + m['X-Calm'] = '1' + + # use utf-8 only if the message can't be ascii encoded + charset = 'ascii' + try: + msg.encode('ascii') + except UnicodeError: + charset = 'utf-8' + m.set_payload(msg, charset=charset) + + # if To: header consists of the single address 'debug', just dump the mail we would have sent + if m['To'] == 'debug': + logging.debug('-' * 40) + for k in m: + logging.debug('%s: %s' % (k, m[k])) + logging.debug('-' * 40) + logging.debug(msg) + logging.debug('-' * 40) + else: + with subprocess.Popen(['/usr/sbin/sendmail', '-t', '-oi', '-f', hdr['From']], stdin=subprocess.PIPE) as p: + p.communicate(m.as_bytes()) + logging.debug('sendmail: msgid %s, exit status %d' % (m['Message-Id'], p.returncode)) |