spam_exporter.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # Python 3.8.0
  2. import smtplib
  3. import time
  4. import imaplib
  5. import email
  6. import traceback
  7. # -------------------------------------------------
  8. #
  9. # Utility to read email from Gmail Using Python
  10. #
  11. # ------------------------------------------------
  12. ORG_EMAIL = "service@choozmo.com"
  13. FROM_EMAIL = "service@choozmo.com"
  14. FROM_PWD = "meohmerayzyvrgdw"
  15. SMTP_SERVER = "imap.gmail.com"
  16. SMTP_PORT = 993
  17. def ext_body(body):
  18. lines=body.split('\n')
  19. for l in lines:
  20. if 'To: ' in l[0:8]:
  21. return l.replace('To: ')
  22. def read_email_from_gmail():
  23. try:
  24. mail = imaplib.IMAP4_SSL(SMTP_SERVER)
  25. mail.login(FROM_EMAIL,FROM_PWD)
  26. # mail.select('inbox')
  27. mail.select('[Gmail]/Spam')
  28. data = mail.search(None, 'ALL')
  29. mail_ids = data[1]
  30. id_list = mail_ids[0].split()
  31. first_email_id = int(id_list[0])
  32. latest_email_id = int(id_list[-1])
  33. for i in range(latest_email_id,first_email_id, -1):
  34. data = mail.fetch(str(i), '(RFC822)' )
  35. for response_part in data:
  36. arr = response_part[0]
  37. if isinstance(arr, tuple):
  38. msg = email.message_from_string(str(arr[1],'utf-8'))
  39. print(msg)
  40. email_subject = msg['subject']
  41. email_from = msg['from']
  42. email_to = msg['to']
  43. email_body = msg.get_payload(decode=True)
  44. # email_body = msg['body']
  45. print('From : ' + email_from + '\n')
  46. print('To : ' + email_to + '\n')
  47. if email_body is not None:
  48. to_addr=str(ext_body(email_body))
  49. if to_addr is not None:
  50. print(to_addr)
  51. # print('Body : ' + email_body + '\n')
  52. # print('Subject : ' + email_subject + '\n')
  53. except Exception as e:
  54. traceback.print_exc()
  55. print(str(e))
  56. read_email_from_gmail()