Add a working (for reading, at least) command-line interface.
[easyotp.git] / SecureInbox.py
blob60a35c73dd1cc2383f4b5cedf741769ff405c11c
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 SecureInbox(object):
12 def __init__(self, username, password):
13 # IMAP SSL for incoming messages
14 self.mail_in = imaplib.IMAP4_SSL("imap.gmail.com", 993)
16 try:
17 typ, data = self.mail_in.login(username, password)
18 except imaplib.error, e:
19 raise "Login failure: %s" % (e,)
20 else:
21 assert typ == "OK", "imap login returned: %s %s" % (status, message)
22 print "Logged in:", typ, data
24 # Always have "Secure" mailbox selected
25 typ, num_msgs = self.mail_in.select(mailbox="Secure")
26 if typ != "OK":
27 raise ("imap select failure: %s %s" % (typ, num_msgs) +
28 "The 'Secure' tag doesn't exist. Tag some of your EMOTP messages" +
29 "using a new label, named 'Secure'")
31 def get_messages(self):
32 msgs = []
34 try:
35 typ, all_msgs_string = self.mail_in.search(None, 'ALL')
36 except imaplib.error, e:
37 raise "imap search failed: %s" % (e,)
39 all_msgs = all_msgs_string[0].split()
40 for num in all_msgs:
41 typ, body = self.mail_in.fetch(num, "(BODY[])")
42 msg = email.message_from_string(body[0][1])
44 body = str(msg.get_payload())
45 subject = msg.get("Subject")
46 sender = msg.get("From")
47 id = msg.get("Message-ID")
49 #print 'Message %s\n%s\n' % (num, data[0][1])
50 if "--EMOTP_BEGIN--" not in body:
51 continue
53 msgs.append({"body": body,
54 "subject": subject,
55 "sender": sender,
56 "id": id,
57 "num": num})
59 return msgs
61 def __del__(self):
62 self.mail_in.close()
63 self.mail_in.logout()
65 def main():
66 ms = SecureInbox("shellreef", getpass.getpass())
68 for m in ms.get_messages():
69 print m["sender"], m["subject"]
71 if __name__ == "__main__":
72 main()