app.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import imaplib
  2. import email
  3. import email.header
  4. import sqlite3
  5. import hashlib
  6. import time
  7. import datetime
  8. conn = sqlite3.connect("mailboxes.db")
  9. conn.row_factory = sqlite3.Row
  10. sql = conn.cursor()
  11. def connect(server, username, password, folder):
  12. c = imaplib.IMAP4_SSL(server)
  13. c.login(username, password)
  14. c.select(folder, readonly=True)
  15. return c
  16. def mailbox(c, id, last_fetch):
  17. today = datetime.datetime.today().strftime("%d-%b-%Y")
  18. if last_fetch:
  19. search_string = "(SINCE " + last_fetch + ")"
  20. else:
  21. search_string = "ALL"
  22. r, data = c.search(None, search_string)
  23. for num in data[0].split():
  24. r, data = c.fetch(num, '(RFC822)')
  25. msg = email.message_from_string(data[0][1])
  26. subject = str(email.header.decode_header(msg['Subject'])[0][0])
  27. mailid = hashlib.sha1(email.header.decode_header(msg['Message-ID'])[0][0]).hexdigest()
  28. sender = email.header.decode_header(msg['From'])[0][0]
  29. print(subject)
  30. sql.execute("SELECT * FROM mails WHERE mailid = ?", (mailid, ))
  31. if sql.fetchone() != None:
  32. continue
  33. sql.execute("INSERT INTO mails (mailid, `date`, `from`, `to`, subject, body, account_id) VALUES (?, ?, ?, ?, ?, ?, ?)", (mailid, 0, sender.decode('utf-8', 'ignore'), 'idk', subject.decode('utf-8', 'ignore'), data[0][1].decode('utf-8', 'ignore'), id))
  34. conn.commit()
  35. # Save attachments
  36. if msg.get_content_maintype() == 'multipart':
  37. for part in msg.walk():
  38. if part.get_content_maintype() != 'multipart' and part.get('Content-Disposition') is not None and part.get_filename() is not None:
  39. filename = str(time.time()) + "_" + part.get_filename()
  40. open('attachments/' + filename, 'wb').write(part.get_payload(decode=True))
  41. sql.execute("UPDATE mails SET has_attachments = 1 WHERE mailid = ?", (mailid, ))
  42. sql.execute("INSERT INTO attachments (mailid, filename) VALUES (?, ?)", (mailid, filename, ))
  43. sql.execute("UPDATE accounts SET last_fetch = ? WHERE id = ?", (today, id,))
  44. def main():
  45. sql.execute("SELECT * FROM accounts")
  46. accounts = sql.fetchall()
  47. for account in accounts:
  48. mailbox(connect(account["server"], account["username"], account["password"], account["folder"]), account["id"], account["last_fetch"])
  49. main()
  50. conn.commit()