imaplib.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  1. """IMAP4 client.
  2. Based on RFC 2060.
  3. Public class: IMAP4
  4. Public variable: Debug
  5. Public functions: Internaldate2tuple
  6. Int2AP
  7. ParseFlags
  8. Time2Internaldate
  9. """
  10. # Author: Piers Lauder <piers@cs.su.oz.au> December 1997.
  11. #
  12. # Authentication code contributed by Donn Cave <donn@u.washington.edu> June 1998.
  13. # String method conversion by ESR, February 2001.
  14. # GET/SETACL contributed by Anthony Baxter <anthony@interlink.com.au> April 2001.
  15. # IMAP4_SSL contributed by Tino Lange <Tino.Lange@isg.de> March 2002.
  16. # GET/SETQUOTA contributed by Andreas Zeidler <az@kreativkombinat.de> June 2002.
  17. # PROXYAUTH contributed by Rick Holbert <holbert.13@osu.edu> November 2002.
  18. # GET/SETANNOTATION contributed by Tomas Lindroos <skitta@abo.fi> June 2005.
  19. __version__ = "2.58"
  20. import binascii, errno, random, re, socket, subprocess, sys, time, calendar
  21. from datetime import datetime, timezone, timedelta
  22. from io import DEFAULT_BUFFER_SIZE
  23. try:
  24. import ssl
  25. HAVE_SSL = True
  26. except ImportError:
  27. HAVE_SSL = False
  28. __all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple",
  29. "Int2AP", "ParseFlags", "Time2Internaldate"]
  30. # Globals
  31. CRLF = b'\r\n'
  32. Debug = 0
  33. IMAP4_PORT = 143
  34. IMAP4_SSL_PORT = 993
  35. AllowedVersions = ('IMAP4REV1', 'IMAP4') # Most recent first
  36. # Maximal line length when calling readline(). This is to prevent
  37. # reading arbitrary length lines. RFC 3501 and 2060 (IMAP 4rev1)
  38. # don't specify a line length. RFC 2683 suggests limiting client
  39. # command lines to 1000 octets and that servers should be prepared
  40. # to accept command lines up to 8000 octets, so we used to use 10K here.
  41. # In the modern world (eg: gmail) the response to, for example, a
  42. # search command can be quite large, so we now use 1M.
  43. _MAXLINE = 1000000
  44. # Commands
  45. Commands = {
  46. # name valid states
  47. 'APPEND': ('AUTH', 'SELECTED'),
  48. 'AUTHENTICATE': ('NONAUTH',),
  49. 'CAPABILITY': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  50. 'CHECK': ('SELECTED',),
  51. 'CLOSE': ('SELECTED',),
  52. 'COPY': ('SELECTED',),
  53. 'CREATE': ('AUTH', 'SELECTED'),
  54. 'DELETE': ('AUTH', 'SELECTED'),
  55. 'DELETEACL': ('AUTH', 'SELECTED'),
  56. 'ENABLE': ('AUTH', ),
  57. 'EXAMINE': ('AUTH', 'SELECTED'),
  58. 'EXPUNGE': ('SELECTED',),
  59. 'FETCH': ('SELECTED',),
  60. 'GETACL': ('AUTH', 'SELECTED'),
  61. 'GETANNOTATION':('AUTH', 'SELECTED'),
  62. 'GETQUOTA': ('AUTH', 'SELECTED'),
  63. 'GETQUOTAROOT': ('AUTH', 'SELECTED'),
  64. 'MYRIGHTS': ('AUTH', 'SELECTED'),
  65. 'LIST': ('AUTH', 'SELECTED'),
  66. 'LOGIN': ('NONAUTH',),
  67. 'LOGOUT': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  68. 'LSUB': ('AUTH', 'SELECTED'),
  69. 'MOVE': ('SELECTED',),
  70. 'NAMESPACE': ('AUTH', 'SELECTED'),
  71. 'NOOP': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  72. 'PARTIAL': ('SELECTED',), # NB: obsolete
  73. 'PROXYAUTH': ('AUTH',),
  74. 'RENAME': ('AUTH', 'SELECTED'),
  75. 'SEARCH': ('SELECTED',),
  76. 'SELECT': ('AUTH', 'SELECTED'),
  77. 'SETACL': ('AUTH', 'SELECTED'),
  78. 'SETANNOTATION':('AUTH', 'SELECTED'),
  79. 'SETQUOTA': ('AUTH', 'SELECTED'),
  80. 'SORT': ('SELECTED',),
  81. 'STARTTLS': ('NONAUTH',),
  82. 'STATUS': ('AUTH', 'SELECTED'),
  83. 'STORE': ('SELECTED',),
  84. 'SUBSCRIBE': ('AUTH', 'SELECTED'),
  85. 'THREAD': ('SELECTED',),
  86. 'UID': ('SELECTED',),
  87. 'UNSUBSCRIBE': ('AUTH', 'SELECTED'),
  88. }
  89. # Patterns to match server responses
  90. Continuation = re.compile(br'\+( (?P<data>.*))?')
  91. Flags = re.compile(br'.*FLAGS \((?P<flags>[^\)]*)\)')
  92. InternalDate = re.compile(br'.*INTERNALDATE "'
  93. br'(?P<day>[ 0123][0-9])-(?P<mon>[A-Z][a-z][a-z])-(?P<year>[0-9][0-9][0-9][0-9])'
  94. br' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
  95. br' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
  96. br'"')
  97. # Literal is no longer used; kept for backward compatibility.
  98. Literal = re.compile(br'.*{(?P<size>\d+)}$', re.ASCII)
  99. MapCRLF = re.compile(br'\r\n|\r|\n')
  100. # We no longer exclude the ']' character from the data portion of the response
  101. # code, even though it violates the RFC. Popular IMAP servers such as Gmail
  102. # allow flags with ']', and there are programs (including imaplib!) that can
  103. # produce them. The problem with this is if the 'text' portion of the response
  104. # includes a ']' we'll parse the response wrong (which is the point of the RFC
  105. # restriction). However, that seems less likely to be a problem in practice
  106. # than being unable to correctly parse flags that include ']' chars, which
  107. # was reported as a real-world problem in issue #21815.
  108. Response_code = re.compile(br'\[(?P<type>[A-Z-]+)( (?P<data>.*))?\]')
  109. Untagged_response = re.compile(br'\* (?P<type>[A-Z-]+)( (?P<data>.*))?')
  110. # Untagged_status is no longer used; kept for backward compatibility
  111. Untagged_status = re.compile(
  112. br'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?', re.ASCII)
  113. # We compile these in _mode_xxx.
  114. _Literal = br'.*{(?P<size>\d+)}$'
  115. _Untagged_status = br'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?'
  116. class IMAP4:
  117. r"""IMAP4 client class.
  118. Instantiate with: IMAP4([host[, port]])
  119. host - host's name (default: localhost);
  120. port - port number (default: standard IMAP4 port).
  121. All IMAP4rev1 commands are supported by methods of the same
  122. name (in lower-case).
  123. All arguments to commands are converted to strings, except for
  124. AUTHENTICATE, and the last argument to APPEND which is passed as
  125. an IMAP4 literal. If necessary (the string contains any
  126. non-printing characters or white-space and isn't enclosed with
  127. either parentheses or double quotes) each string is quoted.
  128. However, the 'password' argument to the LOGIN command is always
  129. quoted. If you want to avoid having an argument string quoted
  130. (eg: the 'flags' argument to STORE) then enclose the string in
  131. parentheses (eg: "(\Deleted)").
  132. Each command returns a tuple: (type, [data, ...]) where 'type'
  133. is usually 'OK' or 'NO', and 'data' is either the text from the
  134. tagged response, or untagged results from command. Each 'data'
  135. is either a string, or a tuple. If a tuple, then the first part
  136. is the header of the response, and the second part contains
  137. the data (ie: 'literal' value).
  138. Errors raise the exception class <instance>.error("<reason>").
  139. IMAP4 server errors raise <instance>.abort("<reason>"),
  140. which is a sub-class of 'error'. Mailbox status changes
  141. from READ-WRITE to READ-ONLY raise the exception class
  142. <instance>.readonly("<reason>"), which is a sub-class of 'abort'.
  143. "error" exceptions imply a program error.
  144. "abort" exceptions imply the connection should be reset, and
  145. the command re-tried.
  146. "readonly" exceptions imply the command should be re-tried.
  147. Note: to use this module, you must read the RFCs pertaining to the
  148. IMAP4 protocol, as the semantics of the arguments to each IMAP4
  149. command are left to the invoker, not to mention the results. Also,
  150. most IMAP servers implement a sub-set of the commands available here.
  151. """
  152. class error(Exception): pass # Logical errors - debug required
  153. class abort(error): pass # Service errors - close and retry
  154. class readonly(abort): pass # Mailbox status changed to READ-ONLY
  155. def __init__(self, host='', port=IMAP4_PORT):
  156. self.debug = Debug
  157. self.state = 'LOGOUT'
  158. self.literal = None # A literal argument to a command
  159. self.tagged_commands = {} # Tagged commands awaiting response
  160. self.untagged_responses = {} # {typ: [data, ...], ...}
  161. self.continuation_response = '' # Last continuation response
  162. self.is_readonly = False # READ-ONLY desired state
  163. self.tagnum = 0
  164. self._tls_established = False
  165. self._mode_ascii()
  166. # Open socket to server.
  167. self.open(host, port)
  168. try:
  169. self._connect()
  170. except Exception:
  171. try:
  172. self.shutdown()
  173. except OSError:
  174. pass
  175. raise
  176. def _mode_ascii(self):
  177. self.utf8_enabled = False
  178. self._encoding = 'ascii'
  179. self.Literal = re.compile(_Literal, re.ASCII)
  180. self.Untagged_status = re.compile(_Untagged_status, re.ASCII)
  181. def _mode_utf8(self):
  182. self.utf8_enabled = True
  183. self._encoding = 'utf-8'
  184. self.Literal = re.compile(_Literal)
  185. self.Untagged_status = re.compile(_Untagged_status)
  186. def _connect(self):
  187. # Create unique tag for this session,
  188. # and compile tagged response matcher.
  189. self.tagpre = Int2AP(random.randint(4096, 65535))
  190. self.tagre = re.compile(br'(?P<tag>'
  191. + self.tagpre
  192. + br'\d+) (?P<type>[A-Z]+) (?P<data>.*)', re.ASCII)
  193. # Get server welcome message,
  194. # request and store CAPABILITY response.
  195. if __debug__:
  196. self._cmd_log_len = 10
  197. self._cmd_log_idx = 0
  198. self._cmd_log = {} # Last `_cmd_log_len' interactions
  199. if self.debug >= 1:
  200. self._mesg('imaplib version %s' % __version__)
  201. self._mesg('new IMAP4 connection, tag=%s' % self.tagpre)
  202. self.welcome = self._get_response()
  203. if 'PREAUTH' in self.untagged_responses:
  204. self.state = 'AUTH'
  205. elif 'OK' in self.untagged_responses:
  206. self.state = 'NONAUTH'
  207. else:
  208. raise self.error(self.welcome)
  209. self._get_capabilities()
  210. if __debug__:
  211. if self.debug >= 3:
  212. self._mesg('CAPABILITIES: %r' % (self.capabilities,))
  213. for version in AllowedVersions:
  214. if not version in self.capabilities:
  215. continue
  216. self.PROTOCOL_VERSION = version
  217. return
  218. raise self.error('server not IMAP4 compliant')
  219. def __getattr__(self, attr):
  220. # Allow UPPERCASE variants of IMAP4 command methods.
  221. if attr in Commands:
  222. return getattr(self, attr.lower())
  223. raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
  224. def __enter__(self):
  225. return self
  226. def __exit__(self, *args):
  227. if self.state == "LOGOUT":
  228. return
  229. try:
  230. self.logout()
  231. except OSError:
  232. pass
  233. # Overridable methods
  234. def _create_socket(self):
  235. # Default value of IMAP4.host is '', but socket.getaddrinfo()
  236. # (which is used by socket.create_connection()) expects None
  237. # as a default value for host.
  238. host = None if not self.host else self.host
  239. sys.audit("imaplib.open", self, self.host, self.port)
  240. return socket.create_connection((host, self.port))
  241. def open(self, host = '', port = IMAP4_PORT):
  242. """Setup connection to remote server on "host:port"
  243. (default: localhost:standard IMAP4 port).
  244. This connection will be used by the routines:
  245. read, readline, send, shutdown.
  246. """
  247. self.host = host
  248. self.port = port
  249. self.sock = self._create_socket()
  250. self.file = self.sock.makefile('rb')
  251. def read(self, size):
  252. """Read 'size' bytes from remote."""
  253. return self.file.read(size)
  254. def readline(self):
  255. """Read line from remote."""
  256. line = self.file.readline(_MAXLINE + 1)
  257. if len(line) > _MAXLINE:
  258. raise self.error("got more than %d bytes" % _MAXLINE)
  259. return line
  260. def send(self, data):
  261. """Send data to remote."""
  262. sys.audit("imaplib.send", self, data)
  263. self.sock.sendall(data)
  264. def shutdown(self):
  265. """Close I/O established in "open"."""
  266. self.file.close()
  267. try:
  268. self.sock.shutdown(socket.SHUT_RDWR)
  269. except OSError as exc:
  270. # The server might already have closed the connection.
  271. # On Windows, this may result in WSAEINVAL (error 10022):
  272. # An invalid operation was attempted.
  273. if (exc.errno != errno.ENOTCONN
  274. and getattr(exc, 'winerror', 0) != 10022):
  275. raise
  276. finally:
  277. self.sock.close()
  278. def socket(self):
  279. """Return socket instance used to connect to IMAP4 server.
  280. socket = <instance>.socket()
  281. """
  282. return self.sock
  283. # Utility methods
  284. def recent(self):
  285. """Return most recent 'RECENT' responses if any exist,
  286. else prompt server for an update using the 'NOOP' command.
  287. (typ, [data]) = <instance>.recent()
  288. 'data' is None if no new messages,
  289. else list of RECENT responses, most recent last.
  290. """
  291. name = 'RECENT'
  292. typ, dat = self._untagged_response('OK', [None], name)
  293. if dat[-1]:
  294. return typ, dat
  295. typ, dat = self.noop() # Prod server for response
  296. return self._untagged_response(typ, dat, name)
  297. def response(self, code):
  298. """Return data for response 'code' if received, or None.
  299. Old value for response 'code' is cleared.
  300. (code, [data]) = <instance>.response(code)
  301. """
  302. return self._untagged_response(code, [None], code.upper())
  303. # IMAP4 commands
  304. def append(self, mailbox, flags, date_time, message):
  305. """Append message to named mailbox.
  306. (typ, [data]) = <instance>.append(mailbox, flags, date_time, message)
  307. All args except `message' can be None.
  308. """
  309. name = 'APPEND'
  310. if not mailbox:
  311. mailbox = 'INBOX'
  312. if flags:
  313. if (flags[0],flags[-1]) != ('(',')'):
  314. flags = '(%s)' % flags
  315. else:
  316. flags = None
  317. if date_time:
  318. date_time = Time2Internaldate(date_time)
  319. else:
  320. date_time = None
  321. literal = MapCRLF.sub(CRLF, message)
  322. if self.utf8_enabled:
  323. literal = b'UTF8 (' + literal + b')'
  324. self.literal = literal
  325. return self._simple_command(name, mailbox, flags, date_time)
  326. def authenticate(self, mechanism, authobject):
  327. """Authenticate command - requires response processing.
  328. 'mechanism' specifies which authentication mechanism is to
  329. be used - it must appear in <instance>.capabilities in the
  330. form AUTH=<mechanism>.
  331. 'authobject' must be a callable object:
  332. data = authobject(response)
  333. It will be called to process server continuation responses; the
  334. response argument it is passed will be a bytes. It should return bytes
  335. data that will be base64 encoded and sent to the server. It should
  336. return None if the client abort response '*' should be sent instead.
  337. """
  338. mech = mechanism.upper()
  339. # XXX: shouldn't this code be removed, not commented out?
  340. #cap = 'AUTH=%s' % mech
  341. #if not cap in self.capabilities: # Let the server decide!
  342. # raise self.error("Server doesn't allow %s authentication." % mech)
  343. self.literal = _Authenticator(authobject).process
  344. typ, dat = self._simple_command('AUTHENTICATE', mech)
  345. if typ != 'OK':
  346. raise self.error(dat[-1].decode('utf-8', 'replace'))
  347. self.state = 'AUTH'
  348. return typ, dat
  349. def capability(self):
  350. """(typ, [data]) = <instance>.capability()
  351. Fetch capabilities list from server."""
  352. name = 'CAPABILITY'
  353. typ, dat = self._simple_command(name)
  354. return self._untagged_response(typ, dat, name)
  355. def check(self):
  356. """Checkpoint mailbox on server.
  357. (typ, [data]) = <instance>.check()
  358. """
  359. return self._simple_command('CHECK')
  360. def close(self):
  361. """Close currently selected mailbox.
  362. Deleted messages are removed from writable mailbox.
  363. This is the recommended command before 'LOGOUT'.
  364. (typ, [data]) = <instance>.close()
  365. """
  366. try:
  367. typ, dat = self._simple_command('CLOSE')
  368. finally:
  369. self.state = 'AUTH'
  370. return typ, dat
  371. def copy(self, message_set, new_mailbox):
  372. """Copy 'message_set' messages onto end of 'new_mailbox'.
  373. (typ, [data]) = <instance>.copy(message_set, new_mailbox)
  374. """
  375. return self._simple_command('COPY', message_set, new_mailbox)
  376. def create(self, mailbox):
  377. """Create new mailbox.
  378. (typ, [data]) = <instance>.create(mailbox)
  379. """
  380. return self._simple_command('CREATE', mailbox)
  381. def delete(self, mailbox):
  382. """Delete old mailbox.
  383. (typ, [data]) = <instance>.delete(mailbox)
  384. """
  385. return self._simple_command('DELETE', mailbox)
  386. def deleteacl(self, mailbox, who):
  387. """Delete the ACLs (remove any rights) set for who on mailbox.
  388. (typ, [data]) = <instance>.deleteacl(mailbox, who)
  389. """
  390. return self._simple_command('DELETEACL', mailbox, who)
  391. def enable(self, capability):
  392. """Send an RFC5161 enable string to the server.
  393. (typ, [data]) = <intance>.enable(capability)
  394. """
  395. if 'ENABLE' not in self.capabilities:
  396. raise IMAP4.error("Server does not support ENABLE")
  397. typ, data = self._simple_command('ENABLE', capability)
  398. if typ == 'OK' and 'UTF8=ACCEPT' in capability.upper():
  399. self._mode_utf8()
  400. return typ, data
  401. def expunge(self):
  402. """Permanently remove deleted items from selected mailbox.
  403. Generates 'EXPUNGE' response for each deleted message.
  404. (typ, [data]) = <instance>.expunge()
  405. 'data' is list of 'EXPUNGE'd message numbers in order received.
  406. """
  407. name = 'EXPUNGE'
  408. typ, dat = self._simple_command(name)
  409. return self._untagged_response(typ, dat, name)
  410. def fetch(self, message_set, message_parts):
  411. """Fetch (parts of) messages.
  412. (typ, [data, ...]) = <instance>.fetch(message_set, message_parts)
  413. 'message_parts' should be a string of selected parts
  414. enclosed in parentheses, eg: "(UID BODY[TEXT])".
  415. 'data' are tuples of message part envelope and data.
  416. """
  417. name = 'FETCH'
  418. typ, dat = self._simple_command(name, message_set, message_parts)
  419. return self._untagged_response(typ, dat, name)
  420. def getacl(self, mailbox):
  421. """Get the ACLs for a mailbox.
  422. (typ, [data]) = <instance>.getacl(mailbox)
  423. """
  424. typ, dat = self._simple_command('GETACL', mailbox)
  425. return self._untagged_response(typ, dat, 'ACL')
  426. def getannotation(self, mailbox, entry, attribute):
  427. """(typ, [data]) = <instance>.getannotation(mailbox, entry, attribute)
  428. Retrieve ANNOTATIONs."""
  429. typ, dat = self._simple_command('GETANNOTATION', mailbox, entry, attribute)
  430. return self._untagged_response(typ, dat, 'ANNOTATION')
  431. def getquota(self, root):
  432. """Get the quota root's resource usage and limits.
  433. Part of the IMAP4 QUOTA extension defined in rfc2087.
  434. (typ, [data]) = <instance>.getquota(root)
  435. """
  436. typ, dat = self._simple_command('GETQUOTA', root)
  437. return self._untagged_response(typ, dat, 'QUOTA')
  438. def getquotaroot(self, mailbox):
  439. """Get the list of quota roots for the named mailbox.
  440. (typ, [[QUOTAROOT responses...], [QUOTA responses]]) = <instance>.getquotaroot(mailbox)
  441. """
  442. typ, dat = self._simple_command('GETQUOTAROOT', mailbox)
  443. typ, quota = self._untagged_response(typ, dat, 'QUOTA')
  444. typ, quotaroot = self._untagged_response(typ, dat, 'QUOTAROOT')
  445. return typ, [quotaroot, quota]
  446. def list(self, directory='""', pattern='*'):
  447. """List mailbox names in directory matching pattern.
  448. (typ, [data]) = <instance>.list(directory='""', pattern='*')
  449. 'data' is list of LIST responses.
  450. """
  451. name = 'LIST'
  452. typ, dat = self._simple_command(name, directory, pattern)
  453. return self._untagged_response(typ, dat, name)
  454. def login(self, user, password):
  455. """Identify client using plaintext password.
  456. (typ, [data]) = <instance>.login(user, password)
  457. NB: 'password' will be quoted.
  458. """
  459. typ, dat = self._simple_command('LOGIN', user, self._quote(password))
  460. if typ != 'OK':
  461. raise self.error(dat[-1])
  462. self.state = 'AUTH'
  463. return typ, dat
  464. def login_cram_md5(self, user, password):
  465. """ Force use of CRAM-MD5 authentication.
  466. (typ, [data]) = <instance>.login_cram_md5(user, password)
  467. """
  468. self.user, self.password = user, password
  469. return self.authenticate('CRAM-MD5', self._CRAM_MD5_AUTH)
  470. def _CRAM_MD5_AUTH(self, challenge):
  471. """ Authobject to use with CRAM-MD5 authentication. """
  472. import hmac
  473. pwd = (self.password.encode('utf-8') if isinstance(self.password, str)
  474. else self.password)
  475. return self.user + " " + hmac.HMAC(pwd, challenge, 'md5').hexdigest()
  476. def logout(self):
  477. """Shutdown connection to server.
  478. (typ, [data]) = <instance>.logout()
  479. Returns server 'BYE' response.
  480. """
  481. self.state = 'LOGOUT'
  482. typ, dat = self._simple_command('LOGOUT')
  483. self.shutdown()
  484. return typ, dat
  485. def lsub(self, directory='""', pattern='*'):
  486. """List 'subscribed' mailbox names in directory matching pattern.
  487. (typ, [data, ...]) = <instance>.lsub(directory='""', pattern='*')
  488. 'data' are tuples of message part envelope and data.
  489. """
  490. name = 'LSUB'
  491. typ, dat = self._simple_command(name, directory, pattern)
  492. return self._untagged_response(typ, dat, name)
  493. def myrights(self, mailbox):
  494. """Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
  495. (typ, [data]) = <instance>.myrights(mailbox)
  496. """
  497. typ,dat = self._simple_command('MYRIGHTS', mailbox)
  498. return self._untagged_response(typ, dat, 'MYRIGHTS')
  499. def namespace(self):
  500. """ Returns IMAP namespaces ala rfc2342
  501. (typ, [data, ...]) = <instance>.namespace()
  502. """
  503. name = 'NAMESPACE'
  504. typ, dat = self._simple_command(name)
  505. return self._untagged_response(typ, dat, name)
  506. def noop(self):
  507. """Send NOOP command.
  508. (typ, [data]) = <instance>.noop()
  509. """
  510. if __debug__:
  511. if self.debug >= 3:
  512. self._dump_ur(self.untagged_responses)
  513. return self._simple_command('NOOP')
  514. def partial(self, message_num, message_part, start, length):
  515. """Fetch truncated part of a message.
  516. (typ, [data, ...]) = <instance>.partial(message_num, message_part, start, length)
  517. 'data' is tuple of message part envelope and data.
  518. """
  519. name = 'PARTIAL'
  520. typ, dat = self._simple_command(name, message_num, message_part, start, length)
  521. return self._untagged_response(typ, dat, 'FETCH')
  522. def proxyauth(self, user):
  523. """Assume authentication as "user".
  524. Allows an authorised administrator to proxy into any user's
  525. mailbox.
  526. (typ, [data]) = <instance>.proxyauth(user)
  527. """
  528. name = 'PROXYAUTH'
  529. return self._simple_command('PROXYAUTH', user)
  530. def rename(self, oldmailbox, newmailbox):
  531. """Rename old mailbox name to new.
  532. (typ, [data]) = <instance>.rename(oldmailbox, newmailbox)
  533. """
  534. return self._simple_command('RENAME', oldmailbox, newmailbox)
  535. def search(self, charset, *criteria):
  536. """Search mailbox for matching messages.
  537. (typ, [data]) = <instance>.search(charset, criterion, ...)
  538. 'data' is space separated list of matching message numbers.
  539. If UTF8 is enabled, charset MUST be None.
  540. """
  541. name = 'SEARCH'
  542. if charset:
  543. if self.utf8_enabled:
  544. raise IMAP4.error("Non-None charset not valid in UTF8 mode")
  545. typ, dat = self._simple_command(name, 'CHARSET', charset, *criteria)
  546. else:
  547. typ, dat = self._simple_command(name, *criteria)
  548. return self._untagged_response(typ, dat, name)
  549. def select(self, mailbox='INBOX', readonly=False):
  550. """Select a mailbox.
  551. Flush all untagged responses.
  552. (typ, [data]) = <instance>.select(mailbox='INBOX', readonly=False)
  553. 'data' is count of messages in mailbox ('EXISTS' response).
  554. Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so
  555. other responses should be obtained via <instance>.response('FLAGS') etc.
  556. """
  557. self.untagged_responses = {} # Flush old responses.
  558. self.is_readonly = readonly
  559. if readonly:
  560. name = 'EXAMINE'
  561. else:
  562. name = 'SELECT'
  563. typ, dat = self._simple_command(name, mailbox)
  564. if typ != 'OK':
  565. self.state = 'AUTH' # Might have been 'SELECTED'
  566. return typ, dat
  567. self.state = 'SELECTED'
  568. if 'READ-ONLY' in self.untagged_responses \
  569. and not readonly:
  570. if __debug__:
  571. if self.debug >= 1:
  572. self._dump_ur(self.untagged_responses)
  573. raise self.readonly('%s is not writable' % mailbox)
  574. return typ, self.untagged_responses.get('EXISTS', [None])
  575. def setacl(self, mailbox, who, what):
  576. """Set a mailbox acl.
  577. (typ, [data]) = <instance>.setacl(mailbox, who, what)
  578. """
  579. return self._simple_command('SETACL', mailbox, who, what)
  580. def setannotation(self, *args):
  581. """(typ, [data]) = <instance>.setannotation(mailbox[, entry, attribute]+)
  582. Set ANNOTATIONs."""
  583. typ, dat = self._simple_command('SETANNOTATION', *args)
  584. return self._untagged_response(typ, dat, 'ANNOTATION')
  585. def setquota(self, root, limits):
  586. """Set the quota root's resource limits.
  587. (typ, [data]) = <instance>.setquota(root, limits)
  588. """
  589. typ, dat = self._simple_command('SETQUOTA', root, limits)
  590. return self._untagged_response(typ, dat, 'QUOTA')
  591. def sort(self, sort_criteria, charset, *search_criteria):
  592. """IMAP4rev1 extension SORT command.
  593. (typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...)
  594. """
  595. name = 'SORT'
  596. #if not name in self.capabilities: # Let the server decide!
  597. # raise self.error('unimplemented extension command: %s' % name)
  598. if (sort_criteria[0],sort_criteria[-1]) != ('(',')'):
  599. sort_criteria = '(%s)' % sort_criteria
  600. typ, dat = self._simple_command(name, sort_criteria, charset, *search_criteria)
  601. return self._untagged_response(typ, dat, name)
  602. def starttls(self, ssl_context=None):
  603. name = 'STARTTLS'
  604. if not HAVE_SSL:
  605. raise self.error('SSL support missing')
  606. if self._tls_established:
  607. raise self.abort('TLS session already established')
  608. if name not in self.capabilities:
  609. raise self.abort('TLS not supported by server')
  610. # Generate a default SSL context if none was passed.
  611. if ssl_context is None:
  612. ssl_context = ssl._create_stdlib_context()
  613. typ, dat = self._simple_command(name)
  614. if typ == 'OK':
  615. self.sock = ssl_context.wrap_socket(self.sock,
  616. server_hostname=self.host)
  617. self.file = self.sock.makefile('rb')
  618. self._tls_established = True
  619. self._get_capabilities()
  620. else:
  621. raise self.error("Couldn't establish TLS session")
  622. return self._untagged_response(typ, dat, name)
  623. def status(self, mailbox, names):
  624. """Request named status conditions for mailbox.
  625. (typ, [data]) = <instance>.status(mailbox, names)
  626. """
  627. name = 'STATUS'
  628. #if self.PROTOCOL_VERSION == 'IMAP4': # Let the server decide!
  629. # raise self.error('%s unimplemented in IMAP4 (obtain IMAP4rev1 server, or re-code)' % name)
  630. typ, dat = self._simple_command(name, mailbox, names)
  631. return self._untagged_response(typ, dat, name)
  632. def store(self, message_set, command, flags):
  633. """Alters flag dispositions for messages in mailbox.
  634. (typ, [data]) = <instance>.store(message_set, command, flags)
  635. """
  636. if (flags[0],flags[-1]) != ('(',')'):
  637. flags = '(%s)' % flags # Avoid quoting the flags
  638. typ, dat = self._simple_command('STORE', message_set, command, flags)
  639. return self._untagged_response(typ, dat, 'FETCH')
  640. def subscribe(self, mailbox):
  641. """Subscribe to new mailbox.
  642. (typ, [data]) = <instance>.subscribe(mailbox)
  643. """
  644. return self._simple_command('SUBSCRIBE', mailbox)
  645. def thread(self, threading_algorithm, charset, *search_criteria):
  646. """IMAPrev1 extension THREAD command.
  647. (type, [data]) = <instance>.thread(threading_algorithm, charset, search_criteria, ...)
  648. """
  649. name = 'THREAD'
  650. typ, dat = self._simple_command(name, threading_algorithm, charset, *search_criteria)
  651. return self._untagged_response(typ, dat, name)
  652. def uid(self, command, *args):
  653. """Execute "command arg ..." with messages identified by UID,
  654. rather than message number.
  655. (typ, [data]) = <instance>.uid(command, arg1, arg2, ...)
  656. Returns response appropriate to 'command'.
  657. """
  658. command = command.upper()
  659. if not command in Commands:
  660. raise self.error("Unknown IMAP4 UID command: %s" % command)
  661. if self.state not in Commands[command]:
  662. raise self.error("command %s illegal in state %s, "
  663. "only allowed in states %s" %
  664. (command, self.state,
  665. ', '.join(Commands[command])))
  666. name = 'UID'
  667. typ, dat = self._simple_command(name, command, *args)
  668. if command in ('SEARCH', 'SORT', 'THREAD'):
  669. name = command
  670. else:
  671. name = 'FETCH'
  672. return self._untagged_response(typ, dat, name)
  673. def unsubscribe(self, mailbox):
  674. """Unsubscribe from old mailbox.
  675. (typ, [data]) = <instance>.unsubscribe(mailbox)
  676. """
  677. return self._simple_command('UNSUBSCRIBE', mailbox)
  678. def xatom(self, name, *args):
  679. """Allow simple extension commands
  680. notified by server in CAPABILITY response.
  681. Assumes command is legal in current state.
  682. (typ, [data]) = <instance>.xatom(name, arg, ...)
  683. Returns response appropriate to extension command `name'.
  684. """
  685. name = name.upper()
  686. #if not name in self.capabilities: # Let the server decide!
  687. # raise self.error('unknown extension command: %s' % name)
  688. if not name in Commands:
  689. Commands[name] = (self.state,)
  690. return self._simple_command(name, *args)
  691. # Private methods
  692. def _append_untagged(self, typ, dat):
  693. if dat is None:
  694. dat = b''
  695. ur = self.untagged_responses
  696. if __debug__:
  697. if self.debug >= 5:
  698. self._mesg('untagged_responses[%s] %s += ["%r"]' %
  699. (typ, len(ur.get(typ,'')), dat))
  700. if typ in ur:
  701. ur[typ].append(dat)
  702. else:
  703. ur[typ] = [dat]
  704. def _check_bye(self):
  705. bye = self.untagged_responses.get('BYE')
  706. if bye:
  707. raise self.abort(bye[-1].decode(self._encoding, 'replace'))
  708. def _command(self, name, *args):
  709. if self.state not in Commands[name]:
  710. self.literal = None
  711. raise self.error("command %s illegal in state %s, "
  712. "only allowed in states %s" %
  713. (name, self.state,
  714. ', '.join(Commands[name])))
  715. for typ in ('OK', 'NO', 'BAD'):
  716. if typ in self.untagged_responses:
  717. del self.untagged_responses[typ]
  718. if 'READ-ONLY' in self.untagged_responses \
  719. and not self.is_readonly:
  720. raise self.readonly('mailbox status changed to READ-ONLY')
  721. tag = self._new_tag()
  722. name = bytes(name, self._encoding)
  723. data = tag + b' ' + name
  724. for arg in args:
  725. if arg is None: continue
  726. if isinstance(arg, str):
  727. arg = bytes(arg, self._encoding)
  728. data = data + b' ' + arg
  729. literal = self.literal
  730. if literal is not None:
  731. self.literal = None
  732. if type(literal) is type(self._command):
  733. literator = literal
  734. else:
  735. literator = None
  736. data = data + bytes(' {%s}' % len(literal), self._encoding)
  737. if __debug__:
  738. if self.debug >= 4:
  739. self._mesg('> %r' % data)
  740. else:
  741. self._log('> %r' % data)
  742. try:
  743. self.send(data + CRLF)
  744. except OSError as val:
  745. raise self.abort('socket error: %s' % val)
  746. if literal is None:
  747. return tag
  748. while 1:
  749. # Wait for continuation response
  750. while self._get_response():
  751. if self.tagged_commands[tag]: # BAD/NO?
  752. return tag
  753. # Send literal
  754. if literator:
  755. literal = literator(self.continuation_response)
  756. if __debug__:
  757. if self.debug >= 4:
  758. self._mesg('write literal size %s' % len(literal))
  759. try:
  760. self.send(literal)
  761. self.send(CRLF)
  762. except OSError as val:
  763. raise self.abort('socket error: %s' % val)
  764. if not literator:
  765. break
  766. return tag
  767. def _command_complete(self, name, tag):
  768. logout = (name == 'LOGOUT')
  769. # BYE is expected after LOGOUT
  770. if not logout:
  771. self._check_bye()
  772. try:
  773. typ, data = self._get_tagged_response(tag, expect_bye=logout)
  774. except self.abort as val:
  775. raise self.abort('command: %s => %s' % (name, val))
  776. except self.error as val:
  777. raise self.error('command: %s => %s' % (name, val))
  778. if not logout:
  779. self._check_bye()
  780. if typ == 'BAD':
  781. raise self.error('%s command error: %s %s' % (name, typ, data))
  782. return typ, data
  783. def _get_capabilities(self):
  784. typ, dat = self.capability()
  785. if dat == [None]:
  786. raise self.error('no CAPABILITY response from server')
  787. dat = str(dat[-1], self._encoding)
  788. dat = dat.upper()
  789. self.capabilities = tuple(dat.split())
  790. def _get_response(self):
  791. # Read response and store.
  792. #
  793. # Returns None for continuation responses,
  794. # otherwise first response line received.
  795. resp = self._get_line()
  796. # Command completion response?
  797. if self._match(self.tagre, resp):
  798. tag = self.mo.group('tag')
  799. if not tag in self.tagged_commands:
  800. raise self.abort('unexpected tagged response: %r' % resp)
  801. typ = self.mo.group('type')
  802. typ = str(typ, self._encoding)
  803. dat = self.mo.group('data')
  804. self.tagged_commands[tag] = (typ, [dat])
  805. else:
  806. dat2 = None
  807. # '*' (untagged) responses?
  808. if not self._match(Untagged_response, resp):
  809. if self._match(self.Untagged_status, resp):
  810. dat2 = self.mo.group('data2')
  811. if self.mo is None:
  812. # Only other possibility is '+' (continuation) response...
  813. if self._match(Continuation, resp):
  814. self.continuation_response = self.mo.group('data')
  815. return None # NB: indicates continuation
  816. raise self.abort("unexpected response: %r" % resp)
  817. typ = self.mo.group('type')
  818. typ = str(typ, self._encoding)
  819. dat = self.mo.group('data')
  820. if dat is None: dat = b'' # Null untagged response
  821. if dat2: dat = dat + b' ' + dat2
  822. # Is there a literal to come?
  823. while self._match(self.Literal, dat):
  824. # Read literal direct from connection.
  825. size = int(self.mo.group('size'))
  826. if __debug__:
  827. if self.debug >= 4:
  828. self._mesg('read literal size %s' % size)
  829. data = self.read(size)
  830. # Store response with literal as tuple
  831. self._append_untagged(typ, (dat, data))
  832. # Read trailer - possibly containing another literal
  833. dat = self._get_line()
  834. self._append_untagged(typ, dat)
  835. # Bracketed response information?
  836. if typ in ('OK', 'NO', 'BAD') and self._match(Response_code, dat):
  837. typ = self.mo.group('type')
  838. typ = str(typ, self._encoding)
  839. self._append_untagged(typ, self.mo.group('data'))
  840. if __debug__:
  841. if self.debug >= 1 and typ in ('NO', 'BAD', 'BYE'):
  842. self._mesg('%s response: %r' % (typ, dat))
  843. return resp
  844. def _get_tagged_response(self, tag, expect_bye=False):
  845. while 1:
  846. result = self.tagged_commands[tag]
  847. if result is not None:
  848. del self.tagged_commands[tag]
  849. return result
  850. if expect_bye:
  851. typ = 'BYE'
  852. bye = self.untagged_responses.pop(typ, None)
  853. if bye is not None:
  854. # Server replies to the "LOGOUT" command with "BYE"
  855. return (typ, bye)
  856. # If we've seen a BYE at this point, the socket will be
  857. # closed, so report the BYE now.
  858. self._check_bye()
  859. # Some have reported "unexpected response" exceptions.
  860. # Note that ignoring them here causes loops.
  861. # Instead, send me details of the unexpected response and
  862. # I'll update the code in `_get_response()'.
  863. try:
  864. self._get_response()
  865. except self.abort as val:
  866. if __debug__:
  867. if self.debug >= 1:
  868. self.print_log()
  869. raise
  870. def _get_line(self):
  871. line = self.readline()
  872. if not line:
  873. raise self.abort('socket error: EOF')
  874. # Protocol mandates all lines terminated by CRLF
  875. if not line.endswith(b'\r\n'):
  876. raise self.abort('socket error: unterminated line: %r' % line)
  877. line = line[:-2]
  878. if __debug__:
  879. if self.debug >= 4:
  880. self._mesg('< %r' % line)
  881. else:
  882. self._log('< %r' % line)
  883. return line
  884. def _match(self, cre, s):
  885. # Run compiled regular expression match method on 's'.
  886. # Save result, return success.
  887. self.mo = cre.match(s)
  888. if __debug__:
  889. if self.mo is not None and self.debug >= 5:
  890. self._mesg("\tmatched %r => %r" % (cre.pattern, self.mo.groups()))
  891. return self.mo is not None
  892. def _new_tag(self):
  893. tag = self.tagpre + bytes(str(self.tagnum), self._encoding)
  894. self.tagnum = self.tagnum + 1
  895. self.tagged_commands[tag] = None
  896. return tag
  897. def _quote(self, arg):
  898. arg = arg.replace('\\', '\\\\')
  899. arg = arg.replace('"', '\\"')
  900. return '"' + arg + '"'
  901. def _simple_command(self, name, *args):
  902. return self._command_complete(name, self._command(name, *args))
  903. def _untagged_response(self, typ, dat, name):
  904. if typ == 'NO':
  905. return typ, dat
  906. if not name in self.untagged_responses:
  907. return typ, [None]
  908. data = self.untagged_responses.pop(name)
  909. if __debug__:
  910. if self.debug >= 5:
  911. self._mesg('untagged_responses[%s] => %s' % (name, data))
  912. return typ, data
  913. if __debug__:
  914. def _mesg(self, s, secs=None):
  915. if secs is None:
  916. secs = time.time()
  917. tm = time.strftime('%M:%S', time.localtime(secs))
  918. sys.stderr.write(' %s.%02d %s\n' % (tm, (secs*100)%100, s))
  919. sys.stderr.flush()
  920. def _dump_ur(self, dict):
  921. # Dump untagged responses (in `dict').
  922. l = dict.items()
  923. if not l: return
  924. t = '\n\t\t'
  925. l = map(lambda x:'%s: "%s"' % (x[0], x[1][0] and '" "'.join(x[1]) or ''), l)
  926. self._mesg('untagged responses dump:%s%s' % (t, t.join(l)))
  927. def _log(self, line):
  928. # Keep log of last `_cmd_log_len' interactions for debugging.
  929. self._cmd_log[self._cmd_log_idx] = (line, time.time())
  930. self._cmd_log_idx += 1
  931. if self._cmd_log_idx >= self._cmd_log_len:
  932. self._cmd_log_idx = 0
  933. def print_log(self):
  934. self._mesg('last %d IMAP4 interactions:' % len(self._cmd_log))
  935. i, n = self._cmd_log_idx, self._cmd_log_len
  936. while n:
  937. try:
  938. self._mesg(*self._cmd_log[i])
  939. except:
  940. pass
  941. i += 1
  942. if i >= self._cmd_log_len:
  943. i = 0
  944. n -= 1
  945. if HAVE_SSL:
  946. class IMAP4_SSL(IMAP4):
  947. """IMAP4 client class over SSL connection
  948. Instantiate with: IMAP4_SSL([host[, port[, keyfile[, certfile[, ssl_context]]]]])
  949. host - host's name (default: localhost);
  950. port - port number (default: standard IMAP4 SSL port);
  951. keyfile - PEM formatted file that contains your private key (default: None);
  952. certfile - PEM formatted certificate chain file (default: None);
  953. ssl_context - a SSLContext object that contains your certificate chain
  954. and private key (default: None)
  955. Note: if ssl_context is provided, then parameters keyfile or
  956. certfile should not be set otherwise ValueError is raised.
  957. for more documentation see the docstring of the parent class IMAP4.
  958. """
  959. def __init__(self, host='', port=IMAP4_SSL_PORT, keyfile=None,
  960. certfile=None, ssl_context=None):
  961. if ssl_context is not None and keyfile is not None:
  962. raise ValueError("ssl_context and keyfile arguments are mutually "
  963. "exclusive")
  964. if ssl_context is not None and certfile is not None:
  965. raise ValueError("ssl_context and certfile arguments are mutually "
  966. "exclusive")
  967. if keyfile is not None or certfile is not None:
  968. import warnings
  969. warnings.warn("keyfile and certfile are deprecated, use a "
  970. "custom ssl_context instead", DeprecationWarning, 2)
  971. self.keyfile = keyfile
  972. self.certfile = certfile
  973. if ssl_context is None:
  974. ssl_context = ssl._create_stdlib_context(certfile=certfile,
  975. keyfile=keyfile)
  976. self.ssl_context = ssl_context
  977. IMAP4.__init__(self, host, port)
  978. def _create_socket(self):
  979. sock = IMAP4._create_socket(self)
  980. return self.ssl_context.wrap_socket(sock,
  981. server_hostname=self.host)
  982. def open(self, host='', port=IMAP4_SSL_PORT):
  983. """Setup connection to remote server on "host:port".
  984. (default: localhost:standard IMAP4 SSL port).
  985. This connection will be used by the routines:
  986. read, readline, send, shutdown.
  987. """
  988. IMAP4.open(self, host, port)
  989. __all__.append("IMAP4_SSL")
  990. class IMAP4_stream(IMAP4):
  991. """IMAP4 client class over a stream
  992. Instantiate with: IMAP4_stream(command)
  993. "command" - a string that can be passed to subprocess.Popen()
  994. for more documentation see the docstring of the parent class IMAP4.
  995. """
  996. def __init__(self, command):
  997. self.command = command
  998. IMAP4.__init__(self)
  999. def open(self, host = None, port = None):
  1000. """Setup a stream connection.
  1001. This connection will be used by the routines:
  1002. read, readline, send, shutdown.
  1003. """
  1004. self.host = None # For compatibility with parent class
  1005. self.port = None
  1006. self.sock = None
  1007. self.file = None
  1008. self.process = subprocess.Popen(self.command,
  1009. bufsize=DEFAULT_BUFFER_SIZE,
  1010. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  1011. shell=True, close_fds=True)
  1012. self.writefile = self.process.stdin
  1013. self.readfile = self.process.stdout
  1014. def read(self, size):
  1015. """Read 'size' bytes from remote."""
  1016. return self.readfile.read(size)
  1017. def readline(self):
  1018. """Read line from remote."""
  1019. return self.readfile.readline()
  1020. def send(self, data):
  1021. """Send data to remote."""
  1022. self.writefile.write(data)
  1023. self.writefile.flush()
  1024. def shutdown(self):
  1025. """Close I/O established in "open"."""
  1026. self.readfile.close()
  1027. self.writefile.close()
  1028. self.process.wait()
  1029. class _Authenticator:
  1030. """Private class to provide en/decoding
  1031. for base64-based authentication conversation.
  1032. """
  1033. def __init__(self, mechinst):
  1034. self.mech = mechinst # Callable object to provide/process data
  1035. def process(self, data):
  1036. ret = self.mech(self.decode(data))
  1037. if ret is None:
  1038. return b'*' # Abort conversation
  1039. return self.encode(ret)
  1040. def encode(self, inp):
  1041. #
  1042. # Invoke binascii.b2a_base64 iteratively with
  1043. # short even length buffers, strip the trailing
  1044. # line feed from the result and append. "Even"
  1045. # means a number that factors to both 6 and 8,
  1046. # so when it gets to the end of the 8-bit input
  1047. # there's no partial 6-bit output.
  1048. #
  1049. oup = b''
  1050. if isinstance(inp, str):
  1051. inp = inp.encode('utf-8')
  1052. while inp:
  1053. if len(inp) > 48:
  1054. t = inp[:48]
  1055. inp = inp[48:]
  1056. else:
  1057. t = inp
  1058. inp = b''
  1059. e = binascii.b2a_base64(t)
  1060. if e:
  1061. oup = oup + e[:-1]
  1062. return oup
  1063. def decode(self, inp):
  1064. if not inp:
  1065. return b''
  1066. return binascii.a2b_base64(inp)
  1067. Months = ' Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ')
  1068. Mon2num = {s.encode():n+1 for n, s in enumerate(Months[1:])}
  1069. def Internaldate2tuple(resp):
  1070. """Parse an IMAP4 INTERNALDATE string.
  1071. Return corresponding local time. The return value is a
  1072. time.struct_time tuple or None if the string has wrong format.
  1073. """
  1074. mo = InternalDate.match(resp)
  1075. if not mo:
  1076. return None
  1077. mon = Mon2num[mo.group('mon')]
  1078. zonen = mo.group('zonen')
  1079. day = int(mo.group('day'))
  1080. year = int(mo.group('year'))
  1081. hour = int(mo.group('hour'))
  1082. min = int(mo.group('min'))
  1083. sec = int(mo.group('sec'))
  1084. zoneh = int(mo.group('zoneh'))
  1085. zonem = int(mo.group('zonem'))
  1086. # INTERNALDATE timezone must be subtracted to get UT
  1087. zone = (zoneh*60 + zonem)*60
  1088. if zonen == b'-':
  1089. zone = -zone
  1090. tt = (year, mon, day, hour, min, sec, -1, -1, -1)
  1091. utc = calendar.timegm(tt) - zone
  1092. return time.localtime(utc)
  1093. def Int2AP(num):
  1094. """Convert integer to A-P string representation."""
  1095. val = b''; AP = b'ABCDEFGHIJKLMNOP'
  1096. num = int(abs(num))
  1097. while num:
  1098. num, mod = divmod(num, 16)
  1099. val = AP[mod:mod+1] + val
  1100. return val
  1101. def ParseFlags(resp):
  1102. """Convert IMAP4 flags response to python tuple."""
  1103. mo = Flags.match(resp)
  1104. if not mo:
  1105. return ()
  1106. return tuple(mo.group('flags').split())
  1107. def Time2Internaldate(date_time):
  1108. """Convert date_time to IMAP4 INTERNALDATE representation.
  1109. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'. The
  1110. date_time argument can be a number (int or float) representing
  1111. seconds since epoch (as returned by time.time()), a 9-tuple
  1112. representing local time, an instance of time.struct_time (as
  1113. returned by time.localtime()), an aware datetime instance or a
  1114. double-quoted string. In the last case, it is assumed to already
  1115. be in the correct format.
  1116. """
  1117. if isinstance(date_time, (int, float)):
  1118. dt = datetime.fromtimestamp(date_time,
  1119. timezone.utc).astimezone()
  1120. elif isinstance(date_time, tuple):
  1121. try:
  1122. gmtoff = date_time.tm_gmtoff
  1123. except AttributeError:
  1124. if time.daylight:
  1125. dst = date_time[8]
  1126. if dst == -1:
  1127. dst = time.localtime(time.mktime(date_time))[8]
  1128. gmtoff = -(time.timezone, time.altzone)[dst]
  1129. else:
  1130. gmtoff = -time.timezone
  1131. delta = timedelta(seconds=gmtoff)
  1132. dt = datetime(*date_time[:6], tzinfo=timezone(delta))
  1133. elif isinstance(date_time, datetime):
  1134. if date_time.tzinfo is None:
  1135. raise ValueError("date_time must be aware")
  1136. dt = date_time
  1137. elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'):
  1138. return date_time # Assume in correct format
  1139. else:
  1140. raise ValueError("date_time not of a known type")
  1141. fmt = '"%d-{}-%Y %H:%M:%S %z"'.format(Months[dt.month])
  1142. return dt.strftime(fmt)
  1143. if __name__ == '__main__':
  1144. # To test: invoke either as 'python imaplib.py [IMAP4_server_hostname]'
  1145. # or 'python imaplib.py -s "rsh IMAP4_server_hostname exec /etc/rimapd"'
  1146. # to test the IMAP4_stream class
  1147. import getopt, getpass
  1148. try:
  1149. optlist, args = getopt.getopt(sys.argv[1:], 'd:s:')
  1150. except getopt.error as val:
  1151. optlist, args = (), ()
  1152. stream_command = None
  1153. for opt,val in optlist:
  1154. if opt == '-d':
  1155. Debug = int(val)
  1156. elif opt == '-s':
  1157. stream_command = val
  1158. if not args: args = (stream_command,)
  1159. if not args: args = ('',)
  1160. host = args[0]
  1161. USER = getpass.getuser()
  1162. PASSWD = getpass.getpass("IMAP password for %s on %s: " % (USER, host or "localhost"))
  1163. test_mesg = 'From: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)sdata...%(lf)s' % {'user':USER, 'lf':'\n'}
  1164. test_seq1 = (
  1165. ('login', (USER, PASSWD)),
  1166. ('create', ('/tmp/xxx 1',)),
  1167. ('rename', ('/tmp/xxx 1', '/tmp/yyy')),
  1168. ('CREATE', ('/tmp/yyz 2',)),
  1169. ('append', ('/tmp/yyz 2', None, None, test_mesg)),
  1170. ('list', ('/tmp', 'yy*')),
  1171. ('select', ('/tmp/yyz 2',)),
  1172. ('search', (None, 'SUBJECT', 'test')),
  1173. ('fetch', ('1', '(FLAGS INTERNALDATE RFC822)')),
  1174. ('store', ('1', 'FLAGS', r'(\Deleted)')),
  1175. ('namespace', ()),
  1176. ('expunge', ()),
  1177. ('recent', ()),
  1178. ('close', ()),
  1179. )
  1180. test_seq2 = (
  1181. ('select', ()),
  1182. ('response',('UIDVALIDITY',)),
  1183. ('uid', ('SEARCH', 'ALL')),
  1184. ('response', ('EXISTS',)),
  1185. ('append', (None, None, None, test_mesg)),
  1186. ('recent', ()),
  1187. ('logout', ()),
  1188. )
  1189. def run(cmd, args):
  1190. M._mesg('%s %s' % (cmd, args))
  1191. typ, dat = getattr(M, cmd)(*args)
  1192. M._mesg('%s => %s %s' % (cmd, typ, dat))
  1193. if typ == 'NO': raise dat[0]
  1194. return dat
  1195. try:
  1196. if stream_command:
  1197. M = IMAP4_stream(stream_command)
  1198. else:
  1199. M = IMAP4(host)
  1200. if M.state == 'AUTH':
  1201. test_seq1 = test_seq1[1:] # Login not needed
  1202. M._mesg('PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION)
  1203. M._mesg('CAPABILITIES = %r' % (M.capabilities,))
  1204. for cmd,args in test_seq1:
  1205. run(cmd, args)
  1206. for ml in run('list', ('/tmp/', 'yy%')):
  1207. mo = re.match(r'.*"([^"]+)"$', ml)
  1208. if mo: path = mo.group(1)
  1209. else: path = ml.split()[-1]
  1210. run('delete', (path,))
  1211. for cmd,args in test_seq2:
  1212. dat = run(cmd, args)
  1213. if (cmd,args) != ('uid', ('SEARCH', 'ALL')):
  1214. continue
  1215. uid = dat[-1].split()
  1216. if not uid: continue
  1217. run('uid', ('FETCH', '%s' % uid[-1],
  1218. '(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)'))
  1219. print('\nAll tests OK.')
  1220. except:
  1221. print('\nTests failed.')
  1222. if not Debug:
  1223. print('''
  1224. If you would like to see debugging output,
  1225. try: %s -d5
  1226. ''' % sys.argv[0])
  1227. raise