mailFunctions.py 4.5 KB

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