imaplib.py 54 KB

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