spellbook/read-imap.py
2022-03-22 11:45:11 +10:00

63 lines
1.9 KiB
Python

import base64, getpass, imaplib, sys, email, email.header, datetime
from email.policy import default
#TODO: Currently this reads every email in the links folder of my inbox
# I need it to only read the newest email or keep track to the emails it has read (later preferably)
# Could probably do that by storing the date somewhere
# This also has yet to be imported into shaarli at all, so one pass through is still required before going with the above
# the big list of links goes here (should probably write this out to a file?)
linkList = []
def process_mailbox(M):
"""
Do something with emails messages in the folder.
For the sake of this example, print some headers.
"""
rv, data = M.search(None, "ALL")
if rv != 'OK':
print("No messages found!")
return
for num in data[0].split():
rv, data = M.fetch(num, '(RFC822)')
if rv != 'OK':
print("ERROR getting message", num)
return
msg = email.message_from_bytes(data[0][1], policy=default)
for part in msg.walk():
links = str(part.get_payload(decode=True))
# cheap hack to only select parts starting with https://
# might be better to remove all the other ones??
# pass if links[3] == 'h' # because some nodes start with <html
# some sort of xml i think
if links[2] == 'h':
links = links[:links.index('*')]
linkList.append(links.split('\\r\\n'))
hdr = email.header.make_header(email.header.decode_header(msg['Subject']))
subject = str(hdr)
#print('Message %s: %s' % (num, subject))
account = "anish@lakhwara.com"
folder = "links"
f = open('/home/soup/usr/secrets/puralek.config')
p = f.readline()
M = imaplib.IMAP4_SSL('imap.fastmail.com')
M.login(account, p)
rv, data = M.select(folder)
if rv == 'OK':
process_mailbox(M)
M.close()
print('logging out')
M.logout()
print(linkList)