You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.8 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. import imaplib
  2. import pathlib
  3. import time
  4. import os
  5. from secrets import token_urlsafe
  6. try:
  7. import imap_settings as settings
  8. except:
  9. raise ValueError("Imap settings file not found, please check the readme")
  10. def connect():
  11. "connect to the IMAP server Inbox"
  12. server = imaplib.IMAP4_SSL(settings.IMAP_HOST)
  13. server.login(settings.IMAP_USER, settings.IMAP_PWD)
  14. tmp, data = server.select('Inbox')
  15. # When you connect to the inbox one of the parameters returned is the
  16. # current number of messages in it
  17. if os.environ.get('NUMMESSAGES') is None:
  18. os.environ["NUMMESSAGES"] = data[0].decode("UTF-8")
  19. return server
  20. def bytesmessage_to_string(msg):
  21. "converts bytes-like message to string"
  22. if type(msg) is bytes:
  23. msg = msg.decode("UTF-8").rstrip()
  24. return msg
  25. else:
  26. return str(msg)
  27. def send(inbox, msg):
  28. "send msg to inbox in MIME format"
  29. server = connect()
  30. tmp, data = server.append(inbox, flags='', date_time=time.time(), message=str(msg).encode("UTF-8"))
  31. server.close()
  32. def recv_all():
  33. """receive a list of all MIME messages from inbox newer than the last message when first connected"""
  34. server = connect()
  35. r = []
  36. tmp, data = server.search(None, 'ALL')
  37. oldermsgid = os.environ.get('NUMMESSAGES')
  38. for num in data[0].split():
  39. if int(num) >= int(oldermsgid):
  40. tmp, data = server.fetch(num, '(RFC822)')
  41. msg = bytesmessage_to_string(data[0][1])
  42. r.append((num, msg))
  43. os.environ["NUMMESSAGES"] = num.decode("UTF-8")
  44. server.close()
  45. return r
  46. def clean_inbox():
  47. """clean all messsages from IMAP inbox"""
  48. print('cleaning IMAP...')
  49. server = connect()
  50. tmp, data = server.search(None, 'ALL')
  51. for num in data[0].split():
  52. server.store(num, '+FLAGS', '\\Deleted')
  53. server.expunge()
  54. server.close()
  55. print('IMAP inbox empty.')
  56. def backup_inbox():
  57. """copy all messsages from IMAP to local backup folder"""
  58. server = connect()
  59. tmp, data = server.search(None, 'ALL')
  60. for num in data[0].split():
  61. tmp, data = server.fetch(num, '(RFC822 BODY[HEADER])')
  62. device = str(data[0][1]).split('From: "')[1].split(' of')[0]
  63. name = device + "_" + token_urlsafe(16) + ".eml"
  64. msg = bytesmessage_to_string(data[0][1])
  65. with open(os.path.join('Backup/TestInbox',name), "wb") as f:
  66. f.write(str(msg).encode())
  67. server.close()
  68. def restore_inbox():
  69. """copy all the messages from the Backup folder to the IMAP inbox"""
  70. server = connect()
  71. backups = pathlib.Path("./Backup/TestInbox")
  72. emails = backups.glob("*.eml")
  73. l = [ path for path in emails ]
  74. for p in l:
  75. with open(p, "rb") as f:
  76. tmp, data = server.append("Inbox", flags='', date_time=p.stat().st_ctime, message=f.read(-1))
  77. server.close()