Skip to content

Instantly share code, notes, and snippets.

@zhasm
Forked from clemesha/twisted_imap4_example.py
Created July 30, 2010 12:36
Show Gist options
  • Save zhasm/500424 to your computer and use it in GitHub Desktop.
Save zhasm/500424 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
"""
Connect to an IMAP4 server with Twisted.
---------------------------------------
Run like so:
$ python twisted_imap4_example.py
This example is slightly Gmail specific,
in that SSL is required, and the correct
server name and ports are set for Gmail.
This solution originally by Phil Mayers, on twisted-python:
http://twistedmatrix.com/pipermail/twisted-python/2009-June/019793.html
"""
from twisted.internet import reactor, protocol, defer
from twisted.mail import imap4
from twisted.internet import ssl
USERNAME = '...'
PASSWORD = '...'
# Gmail specific:
SERVER = 'imap.gmail.com'
PORT = 993
# Gmail requires you connect via SSL, so
#we pass the follow object to 'someclient.connectSSL':
contextFactory = ssl.ClientContextFactory()
def mailboxes(list):
print list
for flags,sep,mbox in list:
print mbox
def loggedin(res, proto):
d = proto.list('','*')
d.addCallback(mailboxes)
return d
def connected(proto):
print "connected", proto
d = proto.login(USERNAME, PASSWORD)
d.addCallback(loggedin, proto)
d.addErrback(failed)
return d
def failed(f):
print "failed", f
return f
def done(_):
reactor.callLater(0, reactor.stop)
def main():
c = protocol.ClientCreator(reactor, imap4.IMAP4Client)
d = c.connectSSL(SERVER, PORT, contextFactory)
d.addCallbacks(connected, failed)
d.addBoth(done)
reactor.callLater(0, main)
reactor.run()
@zhasm
Copy link
Author

zhasm commented Jul 30, 2010

cool. that's exactly what i'm looking for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment