mail.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. import imaplib
  2. import smtplib
  3. import email
  4. import email.header
  5. def sendEmail(to, subject, emailUser, password, smtpServer, smtpPort):
  6. try:
  7. message = 'From: %s\nTo: %s\nSubject: %s\n\n%s' % (emailUser, to, subject, '')
  8. smtpClient = smtplib.SMTP(smtpServer, smtpPort)
  9. smtpClient.ehlo()
  10. smtpClient.starttls()
  11. smtpClient.ehlo()
  12. smtpClient.login(emailUser, password)
  13. smtpClient.sendmail(emailUser,to,message)
  14. smtpClient.close()
  15. except Exception as e:
  16. print('[EMAIL] - Failed to send email to %s from %s, server %s' % (to, emailUser, smtpServer))
  17. print('[EMAIL] - Error: %s' % str(e))
  18. return False
  19. return True
  20. """
  21. How to parse headers from raw email thanks to
  22. https://gist.github.com/robulouski/7441883
  23. Read IMAP4 RFC
  24. """
  25. def getEmailsFromUser(fromEmail, userEmail, password, imapServer, imapPort, listname, subjectFilter=''):
  26. result = []
  27. print('[EMAIL] - Connecting to %s' % imapServer)
  28. M = imaplib.IMAP4_SSL(host=imapServer, port=imapPort)
  29. print(' [+] OK - Connected')
  30. print('[EMAIL] - Logging in as %s' % userEmail)
  31. rv, data = M.login(userEmail, password)
  32. if rv != 'OK':
  33. print(' [-] ERROR logging in')
  34. return
  35. print(' [+] OK - Logged in success')
  36. rv, data = M.select() # Selects default mailbox: inbox
  37. if rv != 'OK':
  38. print(' [-] ERROR getting default mailbox')
  39. return
  40. flags = '(UNSEEN FROM "%s"' % fromEmail
  41. if len(subjectFilter) > 0:
  42. flags = flags + ' SUBJECT "%s"' % subjectFilter
  43. else:
  44. flags = flags + ' NOT SUBJECT "REVIEW %s"' % listname
  45. flags += ')'
  46. print('[EMAIL] - Searching for unseen emails from %s, %s' % (fromEmail, flags))
  47. rv, data = M.search(None, flags) # get emails with the unseen flag
  48. if rv != 'OK':
  49. pass
  50. print('[EMAIL] - Got this email identifiers: %s' % str(data[0]))
  51. for number in data[0].split():
  52. print('[EMAIL] - Fetching email %s' % number)
  53. rv, data = M.fetch(number, '(RFC822)')
  54. if rv != 'OK':
  55. pass
  56. # parsing email
  57. msg = email.message_from_string(data[0][1])
  58. subject = email.header.decode_header(msg['Subject'])[0]
  59. subject = subject[0]
  60. sender = msg['From']
  61. content = ''
  62. if msg.is_multipart():
  63. print(' [+] Email is multipart, concatenating')
  64. content += concatenateMultipartEmail(msg.get_payload())
  65. else:
  66. content += msg.get_payload()
  67. print('\n\n')
  68. print(' [+] Subject: %s' % subject)
  69. print(' [+] From: %s' % sender)
  70. content = content.decode('utf-8')
  71. if not sender or not subject:
  72. return []
  73. if sender.find(fromEmail) != -1:
  74. result.append({
  75. 'subject': subject,
  76. 'from': sender,
  77. 'content': content
  78. })
  79. print('[EMAIL] - Logging out')
  80. M.logout()
  81. return result
  82. def concatenateMultipartEmail(emailMessage):
  83. content = ''
  84. for payload in emailMessage:
  85. if payload.is_multipart():
  86. content += concatenateMultipartEmail(payload.get_payload())
  87. else:
  88. content += payload.get_payload()
  89. return content
  90. def getModerationData(emailContent='', listName='', senderEmail=''):
  91. # print('######################################')
  92. # print('##### Message body from %s ######' % senderEmail)
  93. # print(' %s ' % emailContent)
  94. # print('###### END OF BODY####################')
  95. MODERATION_CODE_PATTERN = 'DISTRIBUTE %s' % listName
  96. senderEmail = ''
  97. index = emailContent.find(senderEmail)
  98. if index == -1:
  99. print '[MOD] - Not found sender email %s' % senderEmail
  100. return None
  101. moderationCode = ''
  102. index = emailContent.find(MODERATION_CODE_PATTERN)
  103. if index == -1:
  104. print '[MOD] - Not found moderation code'
  105. return None
  106. index += len(MODERATION_CODE_PATTERN) + 1
  107. while emailContent[index] != ' ' and emailContent[index] != '\r' and emailContent[index] != '\n':
  108. moderationCode += emailContent[index]
  109. index += 1
  110. return moderationCode