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

66 lines
1.6 KiB
Python
Raw Normal View History

2018-11-29 11:39:53 +01:00
#!/usr/bin/env python3
2018-11-28 15:31:35 +01:00
2018-12-02 12:36:50 +01:00
import sys
2018-11-28 15:31:35 +01:00
import imaplib
2018-11-29 11:39:53 +01:00
import email.header
2018-11-28 15:31:35 +01:00
import datetime
2018-11-29 11:54:54 +01:00
def decode_mime_words(s):
2018-11-30 10:43:25 +01:00
return ''.join(
2018-11-29 11:54:54 +01:00
word.decode(encoding or 'utf8') if isinstance(word, bytes) else word
for word, encoding in email.header.decode_header(s))
2018-11-29 11:39:53 +01:00
def process_mailbox(mailbox, to = None):
rv, data = mailbox.search(None, "(UNSEEN)")
2018-11-28 15:31:35 +01:00
if rv != 'OK':
2018-11-29 11:39:53 +01:00
print("No messages found!")
2018-12-02 12:36:50 +01:00
return False
2018-11-28 15:31:35 +01:00
2018-12-02 12:36:50 +01:00
split = data[0].split()
if len(split) == 0:
return False
for num in split:
2018-11-29 11:39:53 +01:00
rv, data = mailbox.fetch(num, '(BODY.PEEK[])')
2018-11-28 15:31:35 +01:00
if rv != 'OK':
2018-11-29 11:39:53 +01:00
print("ERROR getting message", num)
2018-12-02 12:36:50 +01:00
return False
2018-11-28 15:31:35 +01:00
2018-11-29 11:39:53 +01:00
msg = email.message_from_string(data[0][1].decode())
if to is not None:
print('To: ', to)
print('From:', msg['From'])
2018-11-30 10:43:25 +01:00
subject = decode_mime_words(msg['Subject'])
2018-11-29 11:39:53 +01:00
2018-11-30 10:43:25 +01:00
print('Subject: %s' % decode_mime_words(msg['Subject']))
2018-11-28 15:31:35 +01: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 11:39:53 +01:00
print("Local Date:", local_date.strftime("%a, %d %b %Y %H:%M:%S"))
2018-11-30 10:43:25 +01:00
print()
2018-11-29 11:39:53 +01:00
2018-12-02 12:36:50 +01:00
return True
2018-11-29 11:39:53 +01: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 15:31:35 +01:00
2018-11-29 11:39:53 +01:00
rv, data = mailbox.select("INBOX")
2018-11-28 15:31:35 +01:00
2018-11-29 11:39:53 +01:00
if rv == 'OK':
2018-12-02 12:36:50 +01:00
if process_mailbox(mailbox, account.email):
print(account.link, file=sys.stderr)
2018-11-28 15:31:35 +01:00
2018-11-29 11:39:53 +01:00
mailbox.close()
mailbox.logout()