Add beginnings of a Python user interface:
[easyotp.git] / MailServers.py
blob9d278686e5caafce506b7e1cef5c03e6e1983fec
1 #!/bin/env python
2 # Created:20080603
3 # By Jeff Connelly
5 # Communicate with mail servers
7 import imaplib
8 import getpass
9 import email
11 class MailServers(object):
12 def __init__(self, username, password):
13 self.mail_in = imaplib.IMAP4_SSL("imap.gmail.com", 993)
15 try:
16 typ, data = self.mail_in.login(username, password)
17 except imaplib.error, e:
18 raise "Login failure: %s" % (e,)
19 else:
20 assert typ == "OK", "imap login returned: %s %s" % (status, message)
21 print "Logged in:", typ, data
23 # Always have "Secure" mailbox selected
24 typ, num_msgs = self.mail_in.select(mailbox="Secure")
25 if typ != "OK":
26 raise ("imap select failure: %s %s" % (typ, num_msgs) +
27 "The 'Secure' tag doesn't exist. Tag some of your EMOTP messages" +
28 "using a new label, named 'Secure'")
30 def get_messages(self):
31 msgs = []
33 try:
34 typ, all_msgs_string = self.mail_in.search(None, 'ALL')
35 except imaplib.error, e:
36 raise "imap search failed: %s" % (e,)
38 all_msgs = all_msgs_string[0].split()
39 for num in all_msgs:
40 typ, body = self.mail_in.fetch(num, "(BODY[])")
41 msg = email.message_from_string(body[0][1])
43 body = str(msg.get_payload())
44 subject = msg.get("Subject")
45 sender = msg.get("From")
46 id = msg.get("Message-ID")
48 #print 'Message %s\n%s\n' % (num, data[0][1])
49 if "--EMOTP_BEGIN--" not in body:
50 continue
52 msgs.append({"body": body,
53 "subject": subject,
54 "sender": sender,
55 "id": id,
56 "num": num})
58 return msgs
60 def __del__(self):
61 self.mail_in.close()
62 self.mail_in.logout()
64 def main():
65 ms = MailServers("shellreef", getpass.getpass())
67 for m in ms.get_messages():
68 print m["sender"], m["subject"]
70 if __name__ == "__main__":
71 main()