def process_message(uid, msg: email.message.EmailMessage): try: raw_date = msg.get('Date') local_date = None # Now convert to local date-time date_tuple = email.utils.parsedate_tz(raw_date) if date_tuple: local_date = datetime.datetime.fromtimestamp( email.utils.mktime_tz(date_tuple)) except: raw_date = None local_date = None links = [] try: body = msg.get_body(('html', 'plain')) if body: if body.get_content_type() == 'text/plain': links = links_from_plaintext(body.get_content()) elif body.get_content_type() == 'text/html': links = links_from_html(body.get_content()) except: pass try: msg_to = msg.get('To') except: msg_to = None try: msg_from = msg.get('From') except: msg_from = None try: msg_sub = msg.get('Subject') except: msg_sub = None try: msg_id = msg.get('Message-ID') except: msg_id = None info = { 'uid': uid, 'to': msg_to, 'from': msg_from, 'subject': msg_sub, 'raw_date': raw_date, 'local_date': local_date, 'message-id': msg_id, 'links': links, 'num-links': len(links) } return info
async def handle_message(self, message: email.message.EmailMessage): transactional_mail = False if message.get("Remove-List-Unsubscribe", None): del message["List-Unsubscribe"] del message["Remove-List-Unsubscribe"] transactional_mail = True del message['X-Peer'] del message['X-MailFrom'] del message['X-RcptTo'] await aiosmtplib.send(message, hostname=SMTP_HOST, port=SMTP_PORT) if transactional_mail: log.info( f'Transactional Mail has been sent to {",".join(message.get_all("to", []))}' ) else: log.info( f'Non-Transactional Mail has been sent to {",".join(message.get_all("to", []))}' ) if LOG_CONTENT: for part in message.walk(): # each part is a either non-multipart, or another multipart message # that contains further parts... Message is organized like a tree if part.get_content_type() == 'text/plain': log.info(part.get_payload()) if part.get_content_type() == 'text/html': log.info(part.get_payload())
def match_header(header: str, match: str, msg: email.message.EmailMessage)->bool: s = email.header.decode_header(msg.get(header)) return match in s[0]