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

65 lines
1.8 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
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):
return u''.join(
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-11-28 15:31:35 +01:00
return
for num in data[0].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-11-28 15:31:35 +01:00
return
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'])
decode = email.header.decode_header(msg['Subject'])
2018-11-29 11:54:54 +01:00
subject = decode_mime_words(decode)
2018-11-29 11:39:53 +01:00
print('Subject: %s' % 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-28 15:31:35 +01:00
# with code below you can process text of email
# if msg.is_multipart():
# for payload in msg.get_payload():
# if payload.get_content_maintype() == 'text':
2018-11-29 11:39:53 +01:00
# print(payload.get_payload())
2018-11-28 15:31:35 +01:00
# else:
2018-11-29 11:39:53 +01:00
# print(msg.get_payload())
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':
process_mailbox(mailbox, account.email)
2018-11-28 15:31:35 +01:00
2018-11-29 11:39:53 +01:00
mailbox.close()
mailbox.logout()