Add beginnings of Python user interface, which connects to Gmail via IMAP.
[easyotp.git] / ui.py
blob3cb857bf2319add2aac14d31050923dab078086a
1 #!/bin/env python
3 import imaplib
4 import getpass
5 import email
6 import popen2
8 def setup_imap():
9 mail_in = imaplib.IMAP4_SSL("imap.gmail.com", 993)
11 try:
12 typ, data = mail_in.login("shellreef", getpass.getpass())
13 except imaplib.error, e:
14 print "Login failure: %s" % (e,)
15 raise SystemExit
16 else:
17 assert typ == "OK", "imap login returned: %s %s" % (status, message)
18 print "Logged in:", typ, data
20 typ, num_msgs = mail_in.select(mailbox="Secure")
21 if typ != "OK":
22 print "imap select failure: %s %s" % (typ, num_msgs)
23 print "The 'Secure' tag doesn't exist. Tag some of your EMOTP messages"
24 print "using a new label, named 'Secure'"
25 raise SystemExit
27 try:
28 typ, all_msgs_string = mail_in.search(None, 'ALL')
29 except imaplib.error, e:
30 print "imap search failed: %s" % (e,)
31 raise SystemExit
33 all_msgs = all_msgs_string[0].split()
34 for num in all_msgs:
35 typ, body = mail_in.fetch(num, "(BODY[])")
36 msg = email.message_from_string(body[0][1])
38 body = str(msg.get_payload())
39 subject = msg.get("Subject")
40 sender = msg.get("From")
41 id = msg.get("Message-ID")
43 #print 'Message %s\n%s\n' % (num, data[0][1])
44 if "--EMOTP_BEGIN--" not in body:
45 continue
46 print "%s %s" % (num, subject)
47 print body
49 print otp_decode(body)
51 mail_in.close()
52 mail_in.logout()
54 def otp_decode(ct):
55 o, i, e = popen2.popen3("./cotp -d")
56 i.write(ct)
57 i.close()
58 pt = o.read()
59 errors = e.read()
60 if errors:
61 raise errors
62 return pt
64 # TODO: support padname
65 def otp_encode(pt):
66 o, i, e = popen2.popen3("./cotp -e")
67 i.write(pt)
68 i.close()
69 ct = o.read()
70 errors = e.read()
71 if errors:
72 raise errors
73 return ct