imaplib.IMAP4 now supports the context manager protocol.
Original patch by Tarek Ziadé.
diff --git a/Lib/imaplib.py b/Lib/imaplib.py
index ad104fe..27445dd 100644
--- a/Lib/imaplib.py
+++ b/Lib/imaplib.py
@@ -238,6 +238,14 @@
             return getattr(self, attr.lower())
         raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
 
+    def __enter__(self):
+        return self
+
+    def __exit__(self, *args):
+        try:
+            self.logout()
+        except OSError:
+            pass
 
 
     #       Overridable methods