imaplib.py 53 KB

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