XXX Thank people who contributed (Chris?)
+Fixed charset handling for search, sort and thread
+--------------------------------------------------
+The handling of the *charset* argument for the search, sort and thread
+methods has been fixed.
+
+Any unicode criteria given will now be encoded using the supplied
+charset. The charset must refer to an encoding that is capable of
+handling the criteria's characters or an error will occur.
+
+Any criteria given as bytes will not be changed by IMAPClient, but the
+provided charset will still be passed to the IMAP server. The encoding
+referred to by *charset* should match the actual encoding used for the
+critera.
+
+The tests and documentation for search, sort and thread has updated to
+account for these changes and have also been generally improved.
+
Performance optimsation for parsing message id lists
----------------------------------------------------
A short circuit is now used when parsing a list of message ids which
'UNSEEN'
'SINCE 1-Feb-2011'
- *charset* specifies the character set of the strings in the
- criteria. It defaults to US-ASCII.
+ *charset* specifies the character set of the criteria. It
+ defaults to US-ASCII as this is the only charset that a server
+ is required to support by the RFC.
+
+ Any criteria specified using unicode will be encoded as per
+ *charset*. Specifying a unicode criteria that can not be
+ encoded using *charset* will result in an error.
+
+ Any criteria specified using bytes will not be modified but
+ should use an encoding that matches *charset*.
See :rfc:`3501#section-6.4.4` for more details.
search response (i.e. if a MODSEQ criteria was included in the
search).
"""
- return self._search(normalise_search_criteria(criteria), charset)
+ criteria = normalise_search_criteria(criteria, charset)
+ return self._search(criteria, charset)
def gmail_search(self, query, charset=None):
"""Search using Gmail's X-GM-RAW attribute.
example: ``has:attachment in:unread``
This method only works for IMAP servers that support X-GM-RAW,
- which is only likely to be Gmail.
+ which is only like to be Gmail.
See https://developers.google.com/gmail/imap_extensions#extension_of_the_search_command_x-gm-raw
for more info.
- *charset* specifies the character set used to encode the
- search string. It defaults to US-ASCII.
+ *charset* specifies the encoding for the query string. The
+ documentation for *charset* for :py:meth:`.search`
+ also applies here.
"""
- # the the query is sent as a literal to allow for 7-bit query strings
- if isinstance(query, string_types):
- query = query.encode(charset or 'us-ascii')
- self._imap.literal = query
+ # the the query is sent as a literal to allow for 8-bit query strings
+ self._imap.literal = to_bytes(query, charset or 'us-ascii')
return self._search([b'X-GM-RAW'], charset)
def _search(self, criteria, charset):
+ charset = to_bytes(charset)
+
if self.use_uid:
args = []
if charset:
args.extend([b'CHARSET', charset])
args.extend(criteria)
- typ, data = self._imap.uid('SEARCH', *args)
+ typ, data = self._imap.uid('search' if PY3 else b'search', *args)
else:
typ, data = self._imap.search(charset, *criteria)
- self._checkok('search', typ, data)
+ self._checkok(b'search', typ, data)
return parse_message_list(data)
- def thread(self, algorithm='REFERENCES', criteria='ALL', charset='UTF-8'):
- """Return a list of messages threads matching *criteria*.
-
- Each thread is a list of messages ids.
-
- See :rfc:`5256` for more details.
- """
- algorithm = to_bytes(algorithm)
- if not self.has_capability(b'THREAD=' + algorithm):
- raise ValueError('server does not support %s threading algorithm'
- % algorithm)
-
- if not criteria:
- raise ValueError('no criteria specified')
-
- args = [algorithm]
- if charset:
- args.append(to_bytes(charset))
- args.extend(normalise_search_criteria(criteria))
-
- data = self._command_and_check('thread', *args, uid=True)
- return parse_response(data)
-
def sort(self, sort_criteria, criteria='ALL', charset='UTF-8'):
"""Return a list of message ids sorted by *sort_criteria* and
optionally filtered by *criteria*.
REVERSE SIZE
SUBJECT
- The *criteria* argument is as per search().
+ The *criteria* and *charset* arguments are as per
+ :py:meth:`.search`.
See :rfc:`5256` for full details.
Note that SORT is an extension to the IMAP4 standard so it may
not be supported by all IMAP servers.
"""
- if not criteria:
- raise ValueError('no criteria specified')
-
if not self.has_capability('SORT'):
raise self.Error('The server does not support the SORT extension')
- ids = self._command_and_check('sort',
- seq_to_parenstr_upper(sort_criteria),
- charset,
- *normalise_search_criteria(criteria),
- uid=True, unpack=True)
+ ids = self._command_and_check(
+ b'sort',
+ _normalise_sort_criteria(sort_criteria),
+ to_bytes(charset),
+ *normalise_search_criteria(criteria, charset),
+ uid=True, unpack=True)
return [long(i) for i in ids.split()]
+ def thread(self, algorithm='REFERENCES', criteria='ALL', charset='UTF-8'):
+ """Return a list of messages threads matching *criteria*.
+
+ Each returned thread is a list of messages ids. An example
+ return value containing three message threads::
+
+ ((1, 2), (3,), (4, 5, 6))
+
+ The optional *algorithm* argument specifies the threading
+ algorithm to use.
+
+ The *criteria* and *charset* arguments are as per
+ :py:meth:`.search`.
+
+ See :rfc:`5256` for more details.
+
+ """
+ algorithm = to_bytes(algorithm)
+ if not self.has_capability(b'THREAD=' + algorithm):
+ raise ValueError('server does not support %s threading algorithm'
+ % algorithm)
+
+ if not criteria:
+ raise ValueError('no criteria specified')
+
+ args = [algorithm]
+ if charset:
+ args.append(to_bytes(charset))
+ args.extend(normalise_search_criteria(criteria, charset))
+
+ data = self._command_and_check(b'thread', *args, uid=True)
+ return parse_response(data)
+
def get_flags(self, messages):
"""Return the flags set for each message in *messages*.
assert not kwargs, "unexpected keyword args: " + ', '.join(kwargs)
if uid and self.use_uid:
+ if PY3:
+ command = to_unicode(command) # imaplib must die
typ, data = self._imap.uid(command, *args)
else:
- meth = getattr(self._imap, command)
+ meth = getattr(self._imap, to_unicode(command))
typ, data = meth(*args)
self._checkok(command, typ, data)
if unpack:
def seq_to_parenstr_upper(items):
return _join_and_paren(item.upper() for item in _normalise_text_list(items))
-def normalise_search_criteria(criteria):
+def normalise_search_criteria(criteria, charset=None):
if not criteria:
raise ValueError('no criteria specified')
- return ['(' + item + ')' for item in _normalise_text_list(criteria)]
+ if isinstance(criteria, (text_type, binary_type)):
+ criteria = (criteria,)
+ if not charset:
+ charset = 'us-ascii'
+ return [b'(' + to_bytes(item, charset) + b')' for item in criteria]
+
+def _normalise_sort_criteria(criteria, charset=None):
+ if isinstance(criteria, (text_type, binary_type)):
+ criteria = (criteria,)
+ # This is because imaplib's implementation varies between Python 2 and 3.
+ if PY3:
+ return '(' + ' '.join(to_unicode(item).upper() for item in criteria) + ')'
+ else:
+ return b'(' + b' '.join(to_bytes(item).upper() for item in criteria) + b')'
def _join_and_paren(items):
return '(' + ' '.join(items) + ')'
def _normalise_text_list(items):
if isinstance(items, (text_type, binary_type)):
- items = (to_unicode(items),)
+ items = (items,)
return (to_unicode(c) for c in items)
def join_message_ids(messages):
return s.decode('ascii')
return s
-def to_bytes(s):
+def to_bytes(s, charset='ascii'):
if isinstance(s, text_type):
- return s.encode('ascii')
+ return s.encode(charset)
return s
--===============1534046211==--
""".replace('\n', '\r\n')
+
+SMILE = '\u263a'
+FROWN = '\u2639'
+
+SMILE_MESSAGE = b"""\
+Subject: stuff
+Content-Type: text/plain; charset="UTF-8"
+
+'\xe2\x98\xba'
+""".replace(b'\n', b'\r\n')
+
+
class _TestBase(unittest.TestCase):
conf = None
self.assertEqual(len(ids), 1)
self.assertGreater(ids.modseq, initial_modseq)
+ def test_search_with_unicode(self):
+ self.client.append(self.base_folder, SMILE_MESSAGE)
+
+ self.assertEqual(len(self.client.search('TEXT "%s"' % SMILE, charset='UTF-8')), 1)
+ self.assertEqual(len(self.client.search(['TEXT "%s"' % SMILE], charset='UTF-8')), 1)
+
+ self.assertEqual(len(self.client.search('TEXT "%s"' % FROWN, charset='UTF-8')), 0)
+
def test_gmail_search(self):
self.skip_unless_capable('X-GM-EXT-1', 'Gmail search')
random_string = ''.join(random.sample(string.ascii_letters*20, 64))
msg = 'Subject: something\r\n\r\nFoo\r\n%s\r\n' % random_string
self.client.append(self.base_folder, msg)
- self.client.noop() # For Gmail
ids = self.client.gmail_search(random_string)
self.assertEqual(len(ids), 1)
self.assertEqual(len(ids), 0)
def test_sort(self):
- if not self.client.has_capability('SORT'):
- return self.skipTest("Server doesn't support SORT")
+ self.skip_unless_capable('SORT')
# Add some test messages
msg_tmpl = 'Subject: Test\r\n\r\nBody'
expected = [first_id, first_id - 1, first_id - 2]
self.assertListEqual(messages, expected)
+ def test_sort_with_unicode(self):
+ self.skip_unless_capable('SORT')
+
+ self.client.append(self.base_folder, SMILE_MESSAGE)
+
+ messages = self.client.sort('ARRIVAL', ['TEXT "%s"' % SMILE])
+ self.assertEqual(len(messages), 1)
+
+ messages = self.client.sort('ARRIVAL', ['TEXT "%s"' % FROWN])
+ self.assertEqual(len(messages), 0)
+
def test_thread(self):
- thread_algo = None
- for cap in self.client.capabilities():
- if cap.startswith(b'THREAD='):
- thread_algo = cap.split(b'=')[-1]
- break
- if not thread_algo:
- return self.skipTest("Server doesn't support THREAD")
+ self.skip_unless_capable('THREAD=REFERENCES')
msg_tmpl = 'Subject: %s\r\n\r\nBody'
subjects = ('a', 'b', 'c')
expected = ((first_id,), (first_id + 1,), (first_id + 2,))
self.assertTupleEqual(messages, expected)
+ def test_thread_with_unicode(self):
+ self.skip_unless_capable('THREAD=REFERENCES')
+
+ self.client.append(self.base_folder, SMILE_MESSAGE)
+
+ threads = self.client.thread(criteria=['TEXT "%s"' % SMILE])
+ self.assertEqual(len(threads), 1)
+ self.assertEqual(len(threads[0]), 1)
+
+ threads = self.client.thread(criteria=['TEXT "%s"' % FROWN])
+ self.assertEqual(len(threads), 0)
+
def test_copy(self):
self.append_msg(SIMPLE_MESSAGE)
target_folder = self.add_prefix_to_folder('target')
self.client._cached_capabilities = (b'THREAD=FOO',)
self.assertRaises(ValueError, self.client.thread)
+ def test_charset_with_uid(self):
+ self.client._cached_capabilities = (b'THREAD=REFERENCES',)
+ self.client._imap.uid.return_value = ('OK', [])
+
+ self.client.thread(criteria='\u261e', charset='utf-8')
+
+ self.client._imap.uid.assert_called_once_with('thread', b'REFERENCES', b'utf-8', b'(\xe2\x98\x9e)')
+
+ def test_charset_without_uid(self):
+ self.client._cached_capabilities = (b'THREAD=REFERENCES',)
+ self.client.use_uid = False
+ self.client._imap.thread.return_value = ('OK', [])
+
+ self.client.thread(criteria='\u261e', charset='utf-8')
+
+ self.client._imap.thread.assert_called_once_with(b'REFERENCES', b'utf-8', b'(\xe2\x98\x9e)')
+
def test_all_args_with_uid(self):
self.client._cached_capabilities = (b'THREAD=FOO',)
self.client._imap.uid.return_value = ('OK', [])
self.client.thread(algorithm='FOO', criteria='STUFF', charset='ASCII')
- self.client._imap.uid.assert_called_once_with('thread', b'FOO', b'ASCII', '(STUFF)')
+ self.client._imap.uid.assert_called_once_with('thread', b'FOO', b'ASCII', b'(STUFF)')
def test_all_args_without_uid(self):
self.client.use_uid = False
self.client.thread(algorithm='FOO', criteria='STUFF', charset='ASCII')
- self.client._imap.thread.assert_called_once_with(b'FOO', b'ASCII', '(STUFF)')
+ self.client._imap.thread.assert_called_once_with(b'FOO', b'ASCII', b'(STUFF)')
class TestId(IMAPClientTest):
from __future__ import unicode_literals
+from six import PY3
+
from .imapclient_test import IMAPClientTest
from .testable_imapclient import TestableIMAPClient as IMAPClient
+search_command = 'search' if PY3 else b'search'
+
+
class TestSearch(IMAPClientTest):
def test_with_uid(self):
result = self.client.search('FOO')
- self.client._imap.uid.assert_called_once_with('SEARCH', '(FOO)')
+ self.client._imap.uid.assert_called_once_with(search_command, b'(FOO)')
self.assertEqual(result, [1, 2, 44])
self.assertEqual(result.modseq, None)
result = self.client.search('FOO')
- self.client._imap.uid.assert_called_once_with('SEARCH', '(FOO)')
+ self.client._imap.uid.assert_called_once_with(search_command, b'(FOO)')
self.assertEqual(result, [])
self.assertEqual(result.modseq, None)
result = self.client.search('FOO')
- self.client._imap.search.assert_called_once_with(None, '(FOO)')
+ self.client._imap.search.assert_called_once_with(None, b'(FOO)')
self.assertEqual(result, [1, 2, 44])
self.assertEqual(result.modseq, None)
self.client.use_uid = True
self.client._imap.uid.return_value = ('OK', [b'1 2 44'])
- result = self.client.search('FOO', 'UTF9')
+ result = self.client.search(['UNDELETED', 'TEXT "\u2639"'], 'UTF-8')
self.client._imap.uid.assert_called_once_with(
- 'SEARCH',
- b'CHARSET', 'UTF9',
- '(FOO)')
+ search_command,
+ b'CHARSET', b'UTF-8',
+ b'(UNDELETED)',
+ b'(TEXT "\xe2\x98\xb9")',
+ )
self.assertEqual(result, [1, 2, 44])
def test_without_uid_with_charset(self):
self.client.use_uid = False
self.client._imap.search.return_value = ('OK', [b'1 2 44'])
- result = self.client.search('FOO', 'UTF9')
-
- self.client._imap.search.assert_called_once_with('UTF9', '(FOO)')
- self.assertEqual(result, [1, 2, 44])
-
- def test_with_multiple_criteria_and_charset(self):
- self.client.use_uid = False
- self.client._imap.search.return_value = ('OK', [b'1 2 44'])
-
- result = self.client.search(['FOO', 'BAR'], 'UTF9')
+ result = self.client.search(['UNDELETED', 'TEXT "\u2639"'], 'UTF-8')
- self.client._imap.search.assert_called_once_with('UTF9', '(FOO)', '(BAR)')
+ self.client._imap.search.assert_called_once_with(
+ b'UTF-8',
+ b'(UNDELETED)',
+ b'(TEXT "\xe2\x98\xb9")',
+ )
self.assertEqual(result, [1, 2, 44])
def test_modseq(self):
result = self.client.search(['MODSEQ 40000'])
- self.client._imap.uid.assert_called_once_with('SEARCH', '(MODSEQ 40000)')
+ self.client._imap.uid.assert_called_once_with(search_command, b'(MODSEQ 40000)')
self.assertEqual(result, [1, 2])
self.assertEqual(result.modseq, 51101)
result = self.client.gmail_search('FOO')
- self.client._imap.uid.assert_called_once_with('SEARCH', b'X-GM-RAW')
+ self.client._imap.uid.assert_called_once_with(search_command, b'X-GM-RAW')
self.assertEqual(self.client._imap.literal, b'FOO')
self.assertEqual(result, [1, 2, 44])
self.client.use_uid = True
self.client._imap.uid.return_value = ('OK', [b'1 2 44'])
- result = self.client.gmail_search('\u2620', 'UTF8')
+ result = self.client.gmail_search('\u2620', 'UTF-8')
self.client._imap.uid.assert_called_once_with(
- 'SEARCH',
- b'CHARSET', 'UTF8',
+ search_command,
+ b'CHARSET', b'UTF-8',
b'X-GM-RAW')
self.assertEqual(self.client._imap.literal, b'\xe2\x98\xa0')
self.assertEqual(result, [1, 2, 44])
self.client.use_uid = False
self.client._imap.search.return_value = ('OK', [b'1 2 44'])
- result = self.client.gmail_search('\u2620', 'UTF8')
+ result = self.client.gmail_search('\u2620', 'UTF-8')
- self.client._imap.search.assert_called_once_with('UTF8', b'X-GM-RAW')
+ self.client._imap.search.assert_called_once_with(b'UTF-8', b'X-GM-RAW')
self.assertEqual(self.client._imap.literal, b'\xe2\x98\xa0')
self.assertEqual(result, [1, 2, 44])
--- /dev/null
+# Copyright (c) 2015, Menno Smits
+# Released subject to the New BSD License
+# Please see http://en.wikipedia.org/wiki/BSD_licenses
+
+from __future__ import unicode_literals
+
+from six import PY3
+
+from .imapclient_test import IMAPClientTest
+
+
+sort_command = 'sort' if PY3 else b'sort'
+
+
+class TestSort(IMAPClientTest):
+
+ def setUp(self):
+ super(TestSort, self).setUp()
+ self.client._cached_capabilities = (b'SORT',)
+
+ def test_no_support(self):
+ self.client._cached_capabilities = (b'BLAH',)
+ self.assertRaises(ValueError, self.client.thread)
+
+ def test_without_uid(self):
+ self.client.use_uid = False
+ self.client._imap.sort.return_value = ('OK', [b'9 8 7'])
+
+ ids = self.client.sort('arrival')
+
+ self.client._imap.sort.assert_called_once_with(
+ '(ARRIVAL)',
+ b'UTF-8',
+ b'(ALL)',
+ )
+ self.assertSequenceEqual(ids, [9, 8, 7])
+
+ def test_with_uid(self):
+ self.client.use_uid = True
+ self.client._imap.uid.return_value = ('OK', [b'9 8 7'])
+
+ ids = self.client.sort(['foo', 'bar'])
+
+ self.client._imap.uid.assert_called_once_with(
+ sort_command,
+ '(FOO BAR)',
+ b'UTF-8',
+ b'(ALL)',
+ )
+ self.assertSequenceEqual(ids, [9, 8, 7])
+
+ def test_charset_without_uid(self):
+ self.client.use_uid = False
+ self.client._imap.sort.return_value = ('OK', [''])
+
+ self.client.sort('arrival', criteria=['\u261e', 'UNDELETED'], charset='utf-7')
+
+ self.client._imap.sort.assert_called_once_with(
+ '(ARRIVAL)',
+ b'utf-7',
+ b'(+Jh4-)', b'(UNDELETED)',
+ )
+
+ def test_unicode_with_uid(self):
+ self.client._imap.uid.return_value = ('OK', [''])
+
+ self.client.sort('arrival', criteria=['\u261e', 'UNDELETED'], charset='utf-7')
+
+ self.client._imap.uid.assert_called_once_with(
+ sort_command,
+ '(ARRIVAL)',
+ b'utf-7',
+ b'(+Jh4-)', b'(UNDELETED)',
+ )
def test_iter(self):
self.check(iter([123, 99]), b'123,99')
+
class Test_normalise_search_criteria(unittest.TestCase):
- def check(self, criteria, expected):
- self.assertEqual(normalise_search_criteria(criteria), expected)
+ def check(self, criteria, charset, expected):
+ self.assertEqual(normalise_search_criteria(criteria, charset), expected)
def test_unicode(self):
- self.check('Foo', ['(Foo)'])
+ self.check('Foo', None, [b'(Foo)'])
def test_binary(self):
- self.check(b'FOO', ['(FOO)'])
+ self.check(b'FOO', None, [b'(FOO)'])
+
+ def test_unicode_with_charset(self):
+ self.check('\u263a', 'UTF-8', [b'(\xe2\x98\xba)'])
+
+ def test_binary_with_charset(self):
+ self.check(b'FOO', 'UTF-9', [b'(FOO)'])
def test_tuple(self):
- self.check(('FOO', 'BAR'), ['(FOO)', '(BAR)'])
+ self.check(('FOO', 'BAR'), None, [b'(FOO)', b'(BAR)'])
def test_list(self):
- self.check(['FOO', 'BAR'], ['(FOO)', '(BAR)'])
+ self.check(['FOO', 'BAR'], None, [b'(FOO)', b'(BAR)'])
def test_mixed_list(self):
- self.check(['FOO', b'BAR'], ['(FOO)', '(BAR)'])
+ self.check(['FOO', b'BAR'], None, [b'(FOO)', b'(BAR)'])
def test_None(self):
- self.assertRaises(ValueError, normalise_search_criteria, None)
+ self.assertRaises(ValueError, normalise_search_criteria, None, None)
def test_empty(self):
- self.assertRaises(ValueError, normalise_search_criteria, '')
+ self.assertRaises(ValueError, normalise_search_criteria, '', None)