mailFunctions.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. import imaplib, smtplib, ssl, email, os
  2. from itertools import chain
  3. # format raw string you get from fetching mails
  4. def stringCompiling(inputIterable):
  5. # remove first nested iterables
  6. try:
  7. unitered = list(chain.from_iterable(inputIterable))
  8. except TypeError:
  9. unitered = inputIterable
  10. # remove None Type entries
  11. nonNoneList = []
  12. try:
  13. for item in unitered:
  14. if item is not None:
  15. nonNoneList.append(item)
  16. except TypeError:
  17. return ""
  18. # return non empty values
  19. if len(nonNoneList) >= 1:
  20. return nonNoneList[0]
  21. else:
  22. return ""
  23. def errorMsgExit(error_msg):
  24. print("Error: " + error_msg)
  25. def checkConnection(host, username, password, port):
  26. try:
  27. connection = imaplib.IMAP4_SSL(host, port)
  28. connection.login(username, password)
  29. connection.logout()
  30. return True
  31. except Exception as e:
  32. print(str(e))
  33. return False
  34. def connect(host, username, password, port):
  35. connect = imaplib.IMAP4_SSL(host, port)
  36. connect.login(username, password)
  37. connect.enable("UTF8=ACCEPT")
  38. return connect
  39. def listMailboxes(connection):
  40. mailboxes = connection.list()
  41. formatted_mailbox_list = []
  42. for items in mailboxes:
  43. if type(items) == list:
  44. for raw_box_string in items:
  45. box_string = str(raw_box_string)
  46. # TODO: handle cases when folder contains subfolders
  47. modified_box_string = (box_string[box_string.find('"/" ')+4:-1])
  48. # strip unneeded "'s surrounding the folder name
  49. if modified_box_string.startswith('"') and modified_box_string.endswith('"'):
  50. modified_box_string = modified_box_string[1:-1]
  51. formatted_mailbox_list.append(modified_box_string)
  52. connection.logout()
  53. return formatted_mailbox_list
  54. def fetchMails(connection, inbox):
  55. status, messages = connection.select(inbox)
  56. print("status-------\n" + status)
  57. print("messages-------\n" + str(messages))
  58. # number of top emails to fetch
  59. #N = 3
  60. # total number of emails
  61. messages_int = int(messages[0])
  62. print("message_int------\n" + str(messages_int))
  63. typ, data = connection.search(None, 'ALL')
  64. output_list = []
  65. for num in data[0].split():
  66. output_dict = {}
  67. typ, data = connection.fetch(num, '(RFC822)')
  68. msg = email.message_from_bytes(data[0][1])
  69. #print(msg)
  70. raw_string = email.header.decode_header(msg['Subject'])[0]
  71. print("raw_string: " + str(raw_string))
  72. raw_from = email.header.decode_header(msg['From'])
  73. print("raw_from" + str(raw_from))
  74. try:
  75. raw_to = email.header.decode_header(msg['To'])
  76. except TypeError:
  77. raw_to = [""]
  78. try:
  79. raw_cc = email.header.decode_header(msg['CC'])
  80. except TypeError:
  81. raw_cc = [""]
  82. try:
  83. raw_bcc = email.header.decode_header(msg['BCC'])
  84. except TypeError:
  85. raw_bcc = [""]
  86. print("raw_to" + str(raw_to))
  87. raw_date = email.header.decode_header(msg['Date'])[0]
  88. print("raw_to" + str(raw_date))
  89. raw_msg = str(msg)
  90. primitive_body = raw_msg[raw_msg.find('\n\n'):].strip()
  91. #raw_body = email.header.decode_header(msg['Body'])[0][0]
  92. # set subject to an empty string when not found
  93. try:
  94. if raw_string[1] == 'utf-8':
  95. subject = raw_string[0].raw_string('utf-8')
  96. else:
  97. subject = raw_string[0]
  98. except AttributeError:
  99. subject=""
  100. #print("subject: {}".format(subject))
  101. output_dict['subject'] = subject
  102. output_dict['from'] = stringCompiling(raw_from)
  103. output_dict['cc'] = stringCompiling(raw_cc)
  104. output_dict['bcc'] = stringCompiling(raw_bcc)
  105. output_dict['to'] = stringCompiling(raw_to)
  106. output_dict['date'] = stringCompiling(raw_date)
  107. output_dict['content'] = primitive_body
  108. output_list.append(output_dict)
  109. connection.close()
  110. connection.logout()
  111. return output_list
  112. def sendStarttls(host, sendingMail, receivingMail, password, message="", subject="", port=587, cc=[], bcc=[]):
  113. context = ssl.create_default_context()
  114. if type(cc) is not str:
  115. cc = ",".join(cc)
  116. if type(bcc) is not str:
  117. bcc = ",".join(bcc)
  118. utf8Message = "Subject: " + subject + "\nCC: " + cc + "\nBCC: " + bcc + "\n\n" + message
  119. decoded=utf8Message.encode('cp1252').decode('utf-8')
  120. with smtplib.SMTP(host, port) as serverConnection:
  121. serverConnection.starttls(context=context)
  122. serverConnection.login(sendingMail, password)
  123. serverConnection.sendmail(sendingMail, receivingMail, decoded)
  124. def afetchMails(con):
  125. con.select("Sent")
  126. status, email_ids = con.search(None, "ALL")
  127. if status != 'OK':
  128. raise Exception("Error running imap search for spinvox messages: "
  129. "%s" % status)
  130. print(email_ids[0])
  131. fetch_ids = ','.join(str(email_ids[0]).split())
  132. status, data = con.fetch(3, '(RFC822)')
  133. if status != 'OK':
  134. raise Exception("Error running imap fetch for spinvox message: "
  135. "%s" % status)
  136. for i in range(3,4):
  137. header_msg = email.message_from_string(data[i * 3 + 0][1])
  138. subject = header_msg['Subject'],
  139. print(subject)
  140. date = header_msg['Date'],
  141. print(date)
  142. body = data[i * 3 + 1][1]
  143. print(body)
  144. connection.close()
  145. connection.logout()