Skip to content

Instantly share code, notes, and snippets.

@mikeleg
Last active May 8, 2020 09:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeleg/93aa8cdf7fc2eeb07e2a7c2731674431 to your computer and use it in GitHub Desktop.
Save mikeleg/93aa8cdf7fc2eeb07e2a7c2731674431 to your computer and use it in GitHub Desktop.
Read unsee and unread imap mail
import os
import re
import asyncio
import imaplib
import email
import logging
import logging.config
from typing import NoReturn
import yaml
HOST = ""
USER = ""
PASSWORD = ""
def parse_email_txt(log, subject: str, body: str) -> NoReturn:
try:
pass
except Exception as ex:
log.error(ex, exc_info=True)
def parse_email_html(log, subject: str, body: str) -> NoReturn:
try:
pass
except Exception as ex:
log.error(ex, exc_info=True)
def check_email(log):
log.info("STAR CHECK INBOX")
while True:
time.sleep(10)
try:
imap = imaplib.IMAP4_SSL(HOST)
imap.login(USER, PASSWORD)
imap.select("INBOX", readonly=True)
status, response = imap.search("UTF-8", "(UNSEEN UNANSWERED)")
unread_msg_nums = response[0].split()
log.info("NUOVI MESSAGGI #{}".format(len(unread_msg_nums)))
for e_id in unread_msg_nums:
status, response = imap.fetch(e_id, "(RFC822)")
if status != "OK":
log.error("HO AVUTO PROBLEMI A CARICARE LA MAIL")
continue
msg = email.message_from_string(response[0][1].decode("utf-8"))
log.info("STO PROCESSANDO LA MAIL:{}".format(msg["subject"]))
for part in msg.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True)
parse_email_txt(log, msg["subject"], body)
elif part.get_content_type() == "text/html":
body = part.get_payload(decode=True)
parse_email_html(log, msg["subject"], body)
else:
continue
except Exception as ex:
print(ex)
log.error(ex, exc_info=True)
imap.close()
def setup_config(configfilename: str = "config.yaml", logsdir: str = "logs"):
if not os.path.exists(logsdir):
os.makedirs(logsdir)
with open(configfilename, "r") as config_file:
config = yaml.safe_load(config_file.read())
logging.config.dictConfig(config)
return logging.getLogger(__name__)
def main():
logger = setup_config()
check_email(logger)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment