#!/usr/bin/python3 from email.mime.text import MIMEText from email.header import Header from email.mime.multipart import MIMEMultipart from email.utils import formataddr # from lxml import etree import subprocess from nitpo import Nitpo from sheets import Sheets import docing import re class Emailer(Nitpo): def __init__(self, do_verbose=False): """subscription profiles""" super().__init__() self.sheets = Sheets() self.repis_fufi = None self.do_verbose = do_verbose # self.re_nama = re.compile(r"([^<]+)<([^@]+)@([^>]+)>\s*") self.re_nama = re.compile(r"([^<]+)<([^>]+)>\s*") def prepare(self, maix, what='repis', base='base', only=None): """send the email via file, stores the file in base""" # head_doc = self.sheets.get_result(what + '_head', maix) sheet_fufi = self.sheets.get_sheet_fufi(what + '_head') head_doc = self.sheets.via_system(sheet_fufi, maix) msg = MIMEMultipart("alternative") xp = '/n:headers/n:header' header_eles = head_doc.xpath(xp, namespaces={'n': self.const['ns']}) for header_ele in header_eles: name = header_ele.attrib['name'] value = header_ele.attrib['value'] if self.is_it_ascii(value): msg[name] = value continue if header_ele.get('type') == 'address': out = str(self.make_address(value)) if out is not None: msg[name] = out continue msg[name] = Header(value, 'utf-8') if only != 'html': what_text = what + '_text' if self.has_conf('sheets', what_text): # text = self.sheets.get_result(what_text, maix) # detour via sytem sheet_fufi = self.sheets.get_sheet_fufi(what + '_text') text = self.sheets.via_system(sheet_fufi, maix, is_text=True) part = MIMEText(str(text), "plain") msg.attach(part) if only != 'text': what_html = what + '_html' if self.has_conf('sheets', what_html): # html = self.sheets.get_result(what_html, maix) # detour via sytem sheet_fufi = self.sheets.get_sheet_fufi(what + '_html') html = self.sheets.via_system(sheet_fufi, maix) string = docing.show(html) part = MIMEText(str(string), "html") msg.attach(part) # print(html) mail_fufi = self.conf['folders']['mail'] + '/' + base + '.mail' mail_file = open(mail_fufi, 'w') mail_file.write(msg.as_string()) mail_file.close() mail_command = f"cat {mail_fufi} | /usr/sbin/exim4 -t" if self.has_conf('addresses', 'envelope'): envelope_address = self.conf['addresses']['envelope'] mail_command += f" -f {envelope_address}" out = subprocess.run(mail_command, shell=True, check=True) out = None return out def is_it_ascii(self, string): try: string.encode('ascii') except UnicodeEncodeError: return False return True def make_address(self, nama): out = self.re_nama.match(nama) if(out is None): print(f"emailer can't parse '{nama}'") return None name = out.group(1).strip() emad = out.group(2).strip() # # https://stackoverflow.com/questions/10551933/python-email-module-form-header-from-with-some-unicode-name-email address = formataddr((str(Header(name, 'utf-8')), emad)) return address