SHARE
TWEET

IMAP

TatankaSettantasette Sep 12th, 2019 182 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import os,email,imaplib,socket,requests,logging,http.client
  2. mail_user = os.environ.get('MAIL_USER')
  3. mail_password = os.environ.get('MAIL_PASS')
  4. mail_server = os.environ.get('MAIL_SERVER')
  5. detach_dir = '.'
  6. if mail_user is None or mail_password is None or mail_server is None:
  7.     print ('VARIABILI DI AMBIENTE NON DEFINITE')
  8.     exit(1)
  9. try:
  10.     with imaplib.IMAP4_SSL(mail_server) as m:
  11.         try:
  12.             m.login(mail_user,mail_password)
  13.             m.select("INBOX")
  14.             resp, items = m.search(None, "UNSEEN")
  15.             items = items[0].split()
  16.             for emailid in items:
  17.                 resp, data = m.fetch(emailid, "(RFC822)")
  18.                 email_body = data[0][1] # getting the mail content
  19.                 mail = email.message_from_bytes(email_body) # parsing the mail content to get a mail object
  20.                 if mail.get_content_maintype() != 'multipart':
  21.                     continue
  22.                 for part in mail.walk():
  23.                     if part.get_content_maintype() == 'multipart':
  24.                         continue
  25.                     if part.get('Content-Disposition') is None:
  26.                         continue
  27.                     filename = part.get_filename().lower()
  28.                     if filename.endswith('.xlsx'):
  29.                         att_path = os.path.join(detach_dir, filename)
  30.                         fp = open(att_path, 'wb')
  31.                         fp.write(part.get_payload(decode=True))
  32.                         fp.close()
  33.         except imaplib.IMAP4_SSL.error as e:
  34.             print (e)
  35.             print ("ERRORE")
  36.             exit(1)
  37. except imaplib.IMAP4.error:
  38.     print ("Errore di connessione al server")
  39.     exit(1)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top