From 3d778791f91c1440fb6a5a7418d9549071ee7814 Mon Sep 17 00:00:00 2001 From: Jon Turney Date: Sat, 8 Jul 2023 13:23:11 +0100 Subject: 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. --- calm/utils.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) (limited to 'calm/utils.py') 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)) -- cgit v1.2.3