12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- import imaplib
- import email
- import email.header
- import sqlite3
- import hashlib
- import time
- import datetime
- conn = sqlite3.connect("mailboxes.db")
- conn.row_factory = sqlite3.Row
- sql = conn.cursor()
- def connect(server, username, password, folder):
- c = imaplib.IMAP4_SSL(server)
- c.login(username, password)
- c.select(folder, readonly=True)
- return c
- def mailbox(c, id, last_fetch):
- today = datetime.datetime.today().strftime("%d-%b-%Y")
- if last_fetch:
- search_string = "(SINCE " + last_fetch + ")"
- else:
- search_string = "ALL"
- r, data = c.search(None, search_string)
- for num in data[0].split():
- r, data = c.fetch(num, '(RFC822)')
- msg = email.message_from_string(data[0][1])
- subject = str(email.header.decode_header(msg['Subject'])[0][0])
- mailid = hashlib.sha1(email.header.decode_header(msg['Message-ID'])[0][0]).hexdigest()
- sender = email.header.decode_header(msg['From'])[0][0]
- print(subject)
- sql.execute("SELECT * FROM mails WHERE mailid = ?", (mailid, ))
- if sql.fetchone() != None:
- continue
- 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))
- conn.commit()
- # Save attachments
- if msg.get_content_maintype() == 'multipart':
- for part in msg.walk():
- if part.get_content_maintype() != 'multipart' and part.get('Content-Disposition') is not None and part.get_filename() is not None:
- filename = str(time.time()) + "_" + part.get_filename()
- open('attachments/' + filename, 'wb').write(part.get_payload(decode=True))
- sql.execute("UPDATE mails SET has_attachments = 1 WHERE mailid = ?", (mailid, ))
- sql.execute("INSERT INTO attachments (mailid, filename) VALUES (?, ?)", (mailid, filename, ))
- sql.execute("UPDATE accounts SET last_fetch = ? WHERE id = ?", (today, id,))
- def main():
- sql.execute("SELECT * FROM accounts")
- accounts = sql.fetchall()
- for account in accounts:
- mailbox(connect(account["server"], account["username"], account["password"], account["folder"]), account["id"], account["last_fetch"])
- main()
- conn.commit()
|