app.py 2.0 KB

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