awesome/awesome-wm-widgets/email-widget/read_unread_emails.py

67 lines
1.6 KiB
Python
Raw Normal View History

2018-11-29 10:39:53 +00:00
#!/usr/bin/env python3
2018-11-28 14:31:35 +00:00
2018-12-02 11:36:50 +00:00
import sys
2018-11-28 14:31:35 +00:00
import imaplib
2018-11-29 10:39:53 +00:00
import email.header
2018-11-28 14:31:35 +00:00
import datetime
2018-11-29 10:54:54 +00:00
def decode_mime_words(s):
2018-11-30 09:43:25 +00:00
return ''.join(
2018-11-29 10:54:54 +00:00
word.decode(encoding or 'utf8') if isinstance(word, bytes) else word
for word, encoding in email.header.decode_header(s))
2018-11-29 10:39:53 +00:00
def process_mailbox(mailbox, to = None):
rv, data = mailbox.search(None, "(UNSEEN)")
2018-11-28 14:31:35 +00:00
if rv != 'OK':
2018-11-29 10:39:53 +00:00
print("No messages found!")
2018-12-02 11:36:50 +00:00
return False
2018-11-28 14:31:35 +00:00
2018-12-02 11:36:50 +00:00
split = data[0].split()
if len(split) == 0:
return False
for num in split:
2018-11-29 10:39:53 +00:00
rv, data = mailbox.fetch(num, '(BODY.PEEK[])')
2018-11-28 14:31:35 +00:00
if rv != 'OK':
2018-11-29 10:39:53 +00:00
print("ERROR getting message", num)
2018-12-02 11:36:50 +00:00
return False
2018-11-28 14:31:35 +00:00
2019-02-22 09:54:30 +00:00
msg = email.message_from_bytes(data[0][1])
2018-11-29 10:39:53 +00:00
if to is not None:
print('To: ', to)
print('From:', msg['From'])
2019-02-22 09:54:30 +00:00
2018-11-30 09:43:25 +00:00
subject = decode_mime_words(msg['Subject'])
2018-11-29 10:39:53 +00:00
2019-02-22 09:54:30 +00:00
print('Subject: %s' % subject)
2018-11-28 14:31:35 +00:00
date_tuple = email.utils.parsedate_tz(msg['Date'])
if date_tuple:
local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))
2018-11-29 10:39:53 +00:00
print("Local Date:", local_date.strftime("%a, %d %b %Y %H:%M:%S"))
2018-11-30 09:43:25 +00:00
print()
2018-11-29 10:39:53 +00:00
2018-12-02 11:36:50 +00:00
return True
2018-11-29 10:39:53 +00:00
try:
import credentials
except:
print("Couldn't read crendtials")
exit(1)
for account in credentials.accounts:
mailbox = imaplib.IMAP4_SSL(account.host, 993)
mailbox.login(account.username, account.password)
2018-11-28 14:31:35 +00:00
2018-11-29 10:39:53 +00:00
rv, data = mailbox.select("INBOX")
2018-11-28 14:31:35 +00:00
2018-11-29 10:39:53 +00:00
if rv == 'OK':
2018-12-02 11:36:50 +00:00
if process_mailbox(mailbox, account.email):
print(account.link, file=sys.stderr)
2018-11-28 14:31:35 +00:00
2018-11-29 10:39:53 +00:00
mailbox.close()
mailbox.logout()