Skip to content

Commit

Permalink
View email in terminal
Browse files Browse the repository at this point in the history
  • Loading branch information
aryaminus committed May 26, 2018
1 parent cfdb3d7 commit 132ddce
Show file tree
Hide file tree
Showing 2 changed files with 275 additions and 0 deletions.
119 changes: 119 additions & 0 deletions email-list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import smtplib
import time
import imaplib
import email
import sys
import tempfile

#Opens and reads any emails from Gmail
#In order to use fill in the required fields
#Make sure you adjust Gmail settings accordingly
#by going to settings -> forwarding and POP/IMAP -> enable IMAP
#and also allow access for less secure apps.

def read_email_from_gmail():

FROM_EMAIL = "[email protected]" #Enter the email name
FROM_PWD = "emailonvoice" #Enter email password
SMTP_SERVER = "imap.gmail.com"
NUM_TO_READ = 5 #Replace with number of earliest emails desired

try:

#Establish a connection and login to the Gmail account
mail = imaplib.IMAP4_SSL(SMTP_SERVER)
mail.login(FROM_EMAIL,FROM_PWD)

#Look for all emails in the inbox
mail.select('inbox')
type, data = mail.search(None, 'ALL')

x = 0
idList = []

#Get a list of all the email ids, reverse it so that
#the newest ones are at the front of the list
for id in data[0].rsplit():
idList.append(id)

idList = list(reversed(idList))



#Fetch the first NUM_to_READ email subject lines and
#their recipients
for id in idList:
typ, data = mail.fetch(id, '(RFC822)')

if x >= NUM_TO_READ:
break
else:
x += 1
msg = email.message_from_bytes(data[0][1])

print('Message #', x)
email_subject = msg['subject']
email_from = msg['from']
print('From : ' + email_from)
print('Subject : ' + email_subject + '\n')




#Allow the user to read the content of any emails
while(1):
message_to_read = input("Which message would you like to open? (-1 to quit) ")
message_to_read = int(message_to_read)

#Basic error checking
while (message_to_read < 1) or (message_to_read > NUM_TO_READ):
if (message_to_read == -1):
sys.exit()

print("Please enter a valid message #")
message_to_read = input("Which message would you like to open?")

#Parse the desired email
typ, data = mail.fetch(idList[message_to_read-1], '(RFC822)')
msg = email.message_from_bytes(data[0][1])
#print(msg)

print('\nReading message:\n')

for part in msg.walk():
if part.get_content_type() == "text/plain":
#print(part.get_payload(decode=True).decode('utf-8'))
file = part.get_payload(decode=True).decode('utf-8')
#print(file)

for line in file:
print(line, end = '', flush = True)

print('\n')
#Create a temp file to write email contents to
#and then read from the temporary file
#Note we can replace all the file code with a print statement
#and disregard the whole issue with the temp file
#This was simply for the purpose of using a tempfile with python
'''
tmp = tempfile.NamedTemporaryFile()
with open(tmp.name, 'w') as f:
for part in msg.walk():
if part.get_content_type() == "text/plain":
#print(part.get_payload(decode=True).decode('utf-8'))
file = part.get_payload(decode=True).decode('utf-8')
print(file)
f.write(part.get_payload(decode=True).decode('utf-8'))
with open(tmp.name, 'r') as f:
f.seek(0)
for line in f:
print(line, end = '', flush = True)
'''

except:
sys.exit()


read_email_from_gmail()
156 changes: 156 additions & 0 deletions receive(not working).py
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
#!/usr/local/bin/python

try:
import Tkinter
except ImportError:
import tkinter as Tkinter
import time
import threading
import random
import queue
import socket
import sys
from datetime import datetime

class GuiPart:
def __init__(self, master, queue):
self.queue = queue
# GUI stuff
self.labelArray = []
self.messages = []
# Set up the GUI
self.master = master
self.backgroundColor = 'black'
self.listsize = 10
master.config(bg=self.backgroundColor)
self.board = Tkinter.LabelFrame(self.master, text='Notification Board', bg='Black', fg='Yellow', labelanchor='n', width=170)
self.initLabels()
self.board.pack()

def initLabels(self) :
self.textColorTime = 'cyan'
self.textColorMessage = 'orange'
colorTime = 'blue'
colorMessage = 'red'
for i in range(0,self.listsize):
la = Tkinter.Label(self.board, height=0, width=10, bg=self.backgroundColor, fg=colorTime, anchor=Tkinter.W)
lb = Tkinter.Label(self.board, height=0, width=160, bg=self.backgroundColor, fg=colorMessage)
la.grid(row=i,column=0, sticky=Tkinter.W)
lb.grid(row=i,column=1, sticky=Tkinter.W)
self.labelArray.append((la, lb))
colorTime = self.textColorTime
colorMessage = self.textColorMessage
self.initList()
self.displayList()

def initList(self):
for i in range(0, self.listsize):
t = ''
m = ''
self.messages.append((t,m))

def processIncoming(self):
while self.queue.qsize():
try:
msg = self.queue.get(0)
self.processMessage(msg)
except Queue.Empty:
pass

def processMessage(self, message):
timestamp = datetime.utcnow().strftime('%H:%M:%S')
self.publish(timestamp, message)

def publish(self, msg1, msg2):
self.addToList(msg1, msg2)
self.displayList()

def addToList(self, msg1, msg2):
if len(self.messages) == self.listsize:
self.messages.pop(0)
if (msg1 == None):
msg1 = datetime.utcnow().strftime('%H:%M:%S')
newMessage = (msg1, msg2)
self.messages.append(newMessage)

def displayList(self):
index = self.listsize -1
for t, m in self.messages :
la, lb = self.labelArray[index]
la.config(text=t)
lb.config(text=m)
index = index -1

def destroy(self):
self.master.destroy()

class ThreadedClient:

def __init__(self, master):
self.master = master
# Create the queue
self.queue = queue.Queue()
# Define connection parameters
self.conn = None
self.bindError = False
# Set up the GUI part
self.gui = GuiPart(master, self.queue)
# Set up the thread to do asynchronous I/O
self.running = True
self.commThread = threading.Thread(target=self.workerThreadReceive)
self.commThread.daemon = True
self.commThread.start()
# Start the periodic call in the GUI to check if the queue contains anything
self.periodicCall()

def periodicCall(self):
if not self.running:
self.killApplication()
else :
self.gui.processIncoming()
self.master.after(100, self.periodicCall)

def workerThreadReceive(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try :
s.bind((HOST, PORT))
except socket.error as msg :
#print 'Bind failed. Error code: ' + str(msg[0]) + ' Error message: ' + str(msg[1])
self.running = False
self.bindError = True
return
s.listen(1)
(self.conn, self.addr) = s.accept()
while self.running :
data = self.conn.recv(1024)
if data == 'Q' :
self.conn.sendall('Q')
self.running = False
else :
self.queue.put(data)
reply = 'ACK'
self.conn.sendall(reply)
if self.conn is not None:
self.conn.close()

def killApplication(self):
self.running = False
if (self.conn is None) and (not self.bindError) :
sfake = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sfake.connect((HOST,PORT))
sfake.sendall('Q')
sfake.close()
self.gui.destroy()
sys.exit()


HOST = '' # Symbolic name meaning the local host
PORT = 24073 # Arbitrary non-privileged port

root = Tkinter.Tk()

client = ThreadedClient(root)

root.protocol("WM_DELETE_WINDOW", client.killApplication)
root.mainloop()

0 comments on commit 132ddce

Please sign in to comment.