from __future__ import unicode_literals
-from .six import text_type, PY3, int2byte
-from .pycompat import iter_as_bytes
+from .six import text_type, binary_type, iteritems
class FolderNameError(ValueError):
pass
PRINTABLE = set(range(0x20, 0x26)) | set(range(0x27, 0x7f))
def encode(s):
- """Encode a folder name using IMAP modified UTF-7 encoding
+ """Encode a folder name using IMAP modified UTF-7 encoding.
+
+ Even though we're using "encode" here the output is still a unicode string.
- Input and output types:
- Python 2 - str/unicode to str
- Python 3 - str to bytes
"""
- # This is for Python 2 only. Under Python 3 the input will always be unicode.
- if (not PY3 and isinstance(s, str) and
- sum(n for n in (ord(c) for c in s) if n > 127)):
- raise FolderNameError("%r contains characters not valid in a str "
- "folder name. Convert to unicode first?" % s)
+ if not isinstance(s, text_type):
+ return s
r = []
_in = []
def extend_result_if_chars_buffered():
if _in:
- r.extend([b'&', modified_base64(''.join(_in)), b'-'])
+ r.extend(['&', modified_base64(''.join(_in)), '-'])
del _in[:]
for c in s:
if ord(c) in PRINTABLE:
extend_result_if_chars_buffered()
- r.append(int2byte(ord(c)))
+ r.append(c)
elif c == '&':
extend_result_if_chars_buffered()
- r.append(b'&-')
+ r.append('&-')
else:
_in.append(c)
extend_result_if_chars_buffered()
- return b''.join(r[:])
+ return ''.join(r)
def decode(s):
- """Decode a folder name from IMAP modified UTF-7 encoding to unicode
+ """Decode a folder name from IMAP modified UTF-7 encoding to unicode.
+
+ Even though we're using "decode" here the input may still be a unicode
+ string.
+
+ If the input is bytes, it's first decoded to unicode.
- Input and output types:
- Python 2 - str to unicode
- Python 3 - bytes to str
"""
+ if isinstance(s, binary_type):
+ s = s.decode('latin-1')
+ if not isinstance(s, text_type):
+ return s
+
r = []
_in = []
- for c in iter_as_bytes(s):
- if c == b'&' and not _in:
- _in.append(b'&')
- elif c == b'-' and _in:
+ for c in s:
+ if c == '&' and not _in:
+ _in.append('&')
+ elif c == '-' and _in:
if len(_in) == 1:
r.append('&')
else:
- r.append(modified_unbase64(b''.join(_in[1:])))
+ r.append(modified_unbase64(''.join(_in[1:])))
_in = []
elif _in:
_in.append(c)
else:
r.append(c)
if _in:
- r.append(modified_unbase64(b''.join(_in[1:])))
+ r.append(modified_unbase64(''.join(_in[1:])))
- return ''.join(
- x.decode('latin-1') if not isinstance(x, text_type) else x
- for x in r[:])
+ return ''.join(r)
def modified_base64(s):
- s_utf7 = s.encode('utf-7')
- return s_utf7[1:-1].replace(b'/', b',')
+ # encode to utf-7: '\xff' => b'+AP8-', decode from latin-1 => '+AP8-'
+ s_utf7 = s.encode('utf-7').decode('latin-1')
+ return s_utf7[1:-1].replace('/', ',')
def modified_unbase64(s):
- s_utf7 = b'+' + s.replace(b',', b'/') + b'-'
- return s_utf7.decode('utf-7')
+ s_utf7 = '+' + s.replace(',', '/') + '-'
+ # encode to latin-1: '+AP8-' => b'+AP8-', decode from utf-7 => '\xff'
+ return s_utf7.encode('latin-1').decode('utf-7')
+
+
+def from_bytes(data, folder_encode=True):
+ """Convert bytes to string in lists, tuples and dicts.
+
+ Decode by decoding from latin-1 or modified utf7.
+
+ """
+ if isinstance(data, dict):
+ decoded = {}
+ for key, value in iteritems(data):
+ key = from_bytes(key, folder_encode)
+ value = from_bytes(value, folder_encode)
+ decoded[key] = value
+ return decoded
+ if isinstance(data, list):
+ return [from_bytes(item, folder_encode) for item in data]
+ if isinstance(data, tuple):
+ return tuple([from_bytes(item, folder_encode) for item in data])
+ if folder_encode:
+ return decode(data)
+ if isinstance(data, binary_type):
+ return data.decode('latin-1')
+ return data
except ImportError:
oauth2 = None
-from . import imap_utf7
+from .imap_utf7 import encode as encode_utf7, from_bytes
from .fixed_offset import FixedOffset
-from .six import moves, string_types, iteritems
+from .six import moves, iteritems, text_type, integer_types, PY3
xrange = moves.xrange
+if PY3:
+ long = int # long is just int in python3
+
__all__ = ['IMAPClient', 'DELETED', 'SEEN', 'ANSWERED', 'FLAGGED', 'DRAFT', 'RECENT']
"""Logout, returning the server response.
"""
typ, data = self._imap.logout()
+ data = from_bytes(data, self.folder_encode)
self._check_resp('BYE', 'logout', typ, data)
return data[0]
def capabilities(self):
"""Returns the server capability list.
"""
- return self._imap.capabilities
+ capabilities = from_bytes(self._imap.capabilities, self.folder_encode)
+ return capabilities
def has_capability(self, capability):
"""Return ``True`` if the IMAP server has the given *capability*.
# capabilities may in the future be named SORT2 which is
# still compatible with the current standard and will not
# be detected by this method.
- if capability.upper() in self._imap.capabilities:
+ if capability.upper() in self.capabilities():
return True
else:
return False
return self._do_list('LSUB', directory, pattern)
def _do_list(self, cmd, directory, pattern):
+ if self.folder_encode:
+ directory = encode_utf7(directory)
+ pattern = encode_utf7(pattern)
typ, dat = self._imap._simple_command(cmd, directory, pattern)
+ dat = from_bytes(dat, self.folder_encode)
self._checkok(cmd, typ, dat)
typ, dat = self._imap._untagged_response(typ, dat, cmd)
+ dat = from_bytes(dat, self.folder_encode)
return self._proc_folder_list(dat)
def _proc_folder_list(self, folder_data):
ret = []
parsed = parse_response(folder_data)
while parsed:
- raw_flags, delim, raw_name = parsed[:3]
+ flags, delim, name = parsed[:3]
parsed = parsed[3:]
- flags = [imap_utf7.decode(flag) for flag in raw_flags]
- ret.append((flags, delim, self._decode_folder_name(raw_name)))
+ ret.append((flags, delim, self._parse_folder_name(name)))
return ret
def select_folder(self, folder, readonly=False):
'UIDNEXT': 11,
'UIDVALIDITY': 1239278212}
"""
- self._command_and_check('select', self._encode_folder_name(folder), readonly)
- return self._process_select_response(self._imap.untagged_responses)
+ self._command_and_check('select', self._imap._quote(folder), readonly)
+ untagged = self._imap.untagged_responses
+ untagged = from_bytes(untagged, self.folder_encode)
+ return self._process_select_response(untagged)
def _process_select_response(self, resp):
out = {}
See `RFC 2177 <http://tools.ietf.org/html/rfc2177>`_ for more
information about the IDLE extension.
"""
- self._idle_tag = self._imap._command('IDLE')
- resp = self._imap._get_response()
+ self._idle_tag = from_bytes(self._imap._command('IDLE'), self.folder_encode)
+ resp = from_bytes(self._imap._get_response(), self.folder_encode)
if resp is not None:
raise self.Error('Unexpected IDLE response: %s' % resp)
"""
# make the socket non-blocking so the timeout can be
# implemented for this call
- if self.ssl:
- sock = self._imap.sslobj
- else:
- sock = self._imap.sock
+
+ # in py2, imaplib has sslobj (for ssl connexions), and sock for non-sll
+ # in the py3 version it's just sock
+ sock = getattr(self._imap, 'sslobj', self._imap.sock)
+
sock.setblocking(0)
try:
resps = []
if rs:
while True:
try:
- line = self._imap._get_line()
+ line = from_bytes(self._imap._get_line(), self.folder_encode)
except (socket.timeout, socket.error):
break
else:
"""
if what is None:
what = ('MESSAGES', 'RECENT', 'UIDNEXT', 'UIDVALIDITY', 'UNSEEN')
- elif isinstance(what, string_types):
+ elif isinstance(what, text_type):
what = (what,)
what_ = '(%s)' % (' '.join(what))
- data = self._command_and_check('status', self._encode_folder_name(folder), what_, unpack=True)
+ data = self._command_and_check('status', self._imap._quote(folder), what_, unpack=True)
_, status_items = parse_response([data])
return dict(as_pairs(status_items))
def create_folder(self, folder):
"""Create *folder* on the server returning the server response string.
"""
- return self._command_and_check('create', self._encode_folder_name(folder), unpack=True)
+ return self._command_and_check('create', self._imap._quote(folder), unpack=True)
def rename_folder(self, old_name, new_name):
"""Change the name of a folder on the server.
"""
return self._command_and_check('rename',
- self._encode_folder_name(old_name),
- self._encode_folder_name(new_name),
+ self._imap._quote(old_name),
+ self._imap._quote(new_name),
unpack=True)
def delete_folder(self, folder):
"""Delete *folder* on the server returning the server response string.
"""
- return self._command_and_check('delete', self._encode_folder_name(folder), unpack=True)
+ return self._command_and_check('delete', self._imap._quote(folder), unpack=True)
def folder_exists(self, folder):
"""Return ``True`` if *folder* exists on the server.
"""
- data = self._command_and_check('list', '', self._encode_folder_name(folder))
+ data = self._command_and_check('list', '', self._imap._quote(folder))
data = [x for x in data if x]
return len(data) == 1 and data[0] != None
def subscribe_folder(self, folder):
"""Subscribe to *folder*, returning the server response string.
"""
- return self._command_and_check('subscribe', self._encode_folder_name(folder))
+ return self._command_and_check('subscribe', self._imap._quote(folder))
def unsubscribe_folder(self, folder):
"""Unsubscribe to *folder*, returning the server response string.
"""
- return self._command_and_check('unsubscribe', self._encode_folder_name(folder))
+ return self._command_and_check('unsubscribe', self._imap._quote(folder))
def search(self, criteria='ALL', charset=None):
"""Return a list of messages ids matching *criteria*.
if not criteria:
raise ValueError('no criteria specified')
- if isinstance(criteria, string_types):
+ if isinstance(criteria, text_type):
criteria = (criteria,)
crit_list = ['(%s)' % c for c in criteria]
else:
typ, data = self._imap.search(charset, *crit_list)
+ data = from_bytes(data, self.folder_encode)
+
self._checkok('search', typ, data)
data = data[0]
if data is None: # no untagged responses...
if not self.has_capability('SORT'):
raise self.Error('The server does not support the SORT extension')
- if isinstance(sort_criteria, string_types):
+ if isinstance(sort_criteria, text_type):
sort_criteria = (sort_criteria,)
sort_criteria = seq_to_parenlist([s.upper() for s in sort_criteria])
- if isinstance(criteria, string_types):
+ if isinstance(criteria, text_type):
criteria = (criteria,)
crit_list = ['(%s)' % c for c in criteria]
args.insert(0, 'UID')
tag = self._imap._command(*args)
typ, data = self._imap._command_complete('FETCH', tag)
+ data = from_bytes(data, self.folder_encode)
self._checkok('fetch', typ, data)
typ, data = self._imap._untagged_response(typ, data, 'FETCH')
+ data = from_bytes(data, self.folder_encode)
return parse_fetch_response(data, self.normalise_times, self.use_uid)
def append(self, folder, msg, flags=(), msg_time=None):
time_val = '"%s"' % datetime_to_imap(msg_time)
else:
time_val = None
+ flags = self.quote_encode_flags(flags)
return self._command_and_check('append',
- self._encode_folder_name(folder),
+ self._imap._quote(folder),
seq_to_parenlist(flags),
- time_val, msg,
+ time_val, msg.encode('ascii'),
unpack=True)
def copy(self, messages, folder):
"""
return self._command_and_check('copy',
messages_to_str(messages),
- self._encode_folder_name(folder),
+ self._imap._quote(folder),
uid=True, unpack=True)
def expunge(self):
"""Returns a list of ``(who, acl)`` tuples describing the
access controls for *folder*.
"""
- data = self._command_and_check('getacl', self._encode_folder_name(folder))
+ data = self._command_and_check('getacl', self._imap._quote(folder))
parts = list(response_lexer.TokenSource(data))
parts = parts[1:] # First item is folder name
return [(parts[i], parts[i+1]) for i in xrange(0, len(parts), 2)]
server response string.
"""
return self._command_and_check('setacl',
- self._encode_folder_name(folder),
+ self._imap._quote(folder),
who, what,
unpack=True)
line = self._imap._get_response()
if tagged_commands[tag]:
break
- resps.append(_parse_untagged_response(line))
+ resps.append(_parse_untagged_response(from_bytes(line, self.folder_encode)))
typ, data = tagged_commands.pop(tag)
+ data = from_bytes(data, self.folder_encode)
self._checkok(command, typ, data)
return data[0], resps
uid = pop_with_default(kwargs, 'uid', False)
assert not kwargs, "unexpected keyword args: " + ', '.join(kwargs)
+ if self.folder_encode:
+ # "encode" all args to modified UTF-7 just in case there's folder
+ # names or flags
+ args = [encode_utf7(arg) for arg in args]
+
if uid and self.use_uid:
typ, data = self._imap.uid(command, *args)
else:
meth = getattr(self._imap, command)
typ, data = meth(*args)
+ data = from_bytes(data, self.folder_encode)
self._checkok(command, typ, data)
if unpack:
return data[0]
"""
if not messages:
return {}
+ flags = self.quote_encode_flags(flags)
data = self._command_and_check('store',
messages_to_str(messages),
cmd,
seq_to_parenlist(flags),
uid=True)
- return self._flatten_dict(parse_fetch_response((data)))
+ return self._flatten_dict(parse_fetch_response(data))
def _flatten_dict(self, fetch_dict):
- return dict([
- (msgid, data.values()[0])
+ """Return the msg id with the value of the key which isn't 'SEQ'.
+
+ eg: flatten_dict({1: {'SEQ': 1, 'FLAGS': ('abc', 'def')},
+ 2: {'SEQ': 2, 'FLAGS': ('ghi', 'jkl')})
+ >>> {1: ('abc', 'def'), 2: ('ghi', 'jkl')}
+
+ """
+ # remove all SEQ keys
+ for msgid, data in iteritems(fetch_dict): del data['SEQ']
+
+ # there should now be only one key left per data dict, use its value
+ return dict(
+ (msgid, tuple(data.values())[0])
for msgid, data in iteritems(fetch_dict)
- ])
+ )
- def _decode_folder_name(self, name):
+ def _parse_folder_name(self, name):
if isinstance(name, int):
# Some IMAP implementations return integer folder names
# with quotes. These get parsed to ints so convert them
# back to strings.
- return str(name)
- if self.folder_encode:
- return imap_utf7.decode(name)
+ return text_type(name)
return name
- def _encode_folder_name(self, name):
- if self.folder_encode:
- name = imap_utf7.encode(name)
- # imaplib assumes that if a command argument (in this case a
- # folder name) has double quotes around it, then it doesn't
- # need quoting. This "feature" prevents creation of folders
- # with names that start and end with double quotes.
- #
- # To work around this IMAPClient performs the quoting
- # itself. This adds start and end double quotes which also
- # serves to fool IMAP4._checkquote into not attempting further
- # quoting. A hack but it works.
- return _quote_arg(name)
-
def __debug_get(self):
return self._imap.debug
self.log_file.write('%s %s\n' % (datetime.now().strftime('%M:%S.%f'), text))
self.log_file.flush()
+ def quote_encode_flags(self, flags):
+ """Encode to modified utf-7 if needed and quote."""
+ if isinstance(flags, text_type):
+ flags = (flags,)
+ flags = [self._imap._quote(flag) for flag in flags]
+ if self.folder_encode:
+ flags = [encode_utf7(flag) for flag in flags]
+ return flags
+
def messages_to_str(messages):
"""Convert a sequence of messages ids or a single integer message id
into an id list string for use with IMAP commands
"""
- if isinstance(messages, (str, int, long)):
+ if isinstance(messages, (text_type, integer_types)):
messages = (messages,)
elif not isinstance(messages, (tuple, list)):
raise ValueError('invalid message list: %r' % messages)
- return ','.join([str(m) for m in messages])
-
-def seq_to_parenlist(flags):
- """Convert a sequence of strings into parenthised list string for
- use with IMAP commands.
- """
- if isinstance(flags, str):
- flags = (flags,)
- elif not isinstance(flags, (tuple, list)):
- raise ValueError('invalid flags list: %r' % flags)
- return '(%s)' % ' '.join(flags)
+ return ','.join([text_type(m) for m in messages])
def datetime_to_imap(dt):
"""Convert a datetime instance to a IMAP datetime string.
dt = dt.replace(tzinfo=FixedOffset.for_system())
return dt.strftime("%d-%b-%Y %H:%M:%S %z")
-def _quote_arg(arg):
- arg = arg.replace('\\', '\\\\')
- arg = arg.replace('"', '\\"')
- return '"%s"' % arg
+def seq_to_parenlist(flags):
+ """Convert a sequence of strings into parenthised list string for
+ use with IMAP commands.
+ """
+ if isinstance(flags, text_type):
+ flags = (flags,)
+ elif not isinstance(flags, (tuple, list)):
+ raise ValueError('invalid flags list: %r' % flags)
+ return '(%s)' % ' '.join(flags)
def _parse_untagged_response(text):
assert text.startswith('* ')
from email.utils import make_msgid
import imapclient
-from imapclient.six import string_types
+from imapclient.six import text_type
from imapclient.test.util import unittest
from imapclient.config import parse_config_file, create_client_from_config
new_folder = folder + 'x'
resp = self.client.rename_folder(folder, new_folder)
- self.assertIsInstance(resp, str)
+ self.assertIsInstance(resp, text_type)
self.assertTrue(len(resp) > 0)
self.assertFalse(self.client.folder_exists(folder))
# Append message
resp = self.client.append(self.base_folder, SIMPLE_MESSAGE, ('abc', 'def'), msg_time)
- self.assertIsInstance(resp, str)
+ self.assertIsInstance(resp, text_type)
# Retrieve the just added message and check that all looks well
self.assertEqual(self.client.select_folder(self.base_folder)['EXISTS'], 1)
resp = self.client.fetch(self.client.search()[0], ('RFC822', 'FLAGS', 'INTERNALDATE'))
self.assertEqual(len(resp), 1)
- msginfo = resp.values()[0]
+ msginfo = tuple(resp.values())[0]
# Time should match the time we specified
returned_msg_time = msginfo['INTERNALDATE']
def _flagtest(func, args, expected_flags):
answer = func(msg_id, *args)
- self.assertTrue(answer.has_key(msg_id))
+ self.assertTrue(msg_id in answer)
answer_flags = set(answer[msg_id])
answer_flags.discard(r'\Recent') # Might be present but don't care
self.assertSetEqual(answer_flags, set(expected_flags))
def _labeltest(func, args, expected_labels):
answer = func(msg_id, *args)
- self.assertEquals(answer.keys(), [msg_id])
+ self.assertEqual(list(answer.keys()), [msg_id])
actual_labels = set(answer[msg_id])
self.assertSetEqual(actual_labels, set(expected_labels))
responses = self.client.idle_check(timeout=5)
text, more_responses = self.client.idle_done()
self.assertIn((1, 'EXISTS'), responses)
- self.assertTrue(isinstance(text, str))
+ self.assertTrue(isinstance(text, text_type))
self.assertGreater(len(text), 0)
self.assertTrue(isinstance(more_responses, list))
text, responses = self.client.idle_done()
self.assertIn((2, 'EXISTS'), responses)
- self.assertTrue(isinstance(text, str))
+ self.assertTrue(isinstance(text, text_type))
self.assertGreater(len(text), 0)
def test_noop(self):
# Initially there should be no responses
text, resps = self.client.noop()
- self.assertTrue(isinstance(text, str))
+ self.assertTrue(isinstance(text, text_type))
self.assertGreater(len(text), 0)
- self.assertEquals(resps, [])
+ self.assertEqual(resps, [])
# Start a new connection and upload a new message
client2 = create_client_from_config(conf)
# Check for this addition in the NOOP data
msg, resps = self.client.noop()
- self.assertTrue(isinstance(text, str))
+ self.assertTrue(isinstance(text, text_type))
self.assertGreater(len(text), 0)
self.assertTrue(isinstance(resps, list))
self.assertIn((1, 'EXISTS'), resps)
# Test empty mailbox
text, resps = self.client.expunge()
- self.assertTrue(isinstance(text, str))
+ self.assertTrue(isinstance(text, text_type))
self.assertGreater(len(text), 0)
# Some servers return nothing while others (e.g. Exchange) return (0, 'EXISTS')
self.assertIn(resps, ([], [(0, 'EXISTS')]))
msg, resps = self.client.expunge()
- self.assertTrue(isinstance(text, str))
+ self.assertTrue(isinstance(text, text_type))
self.assertGreater(len(text), 0)
self.assertTrue(isinstance(resps, list))
if not self.is_gmail():
def lower_if_str(val):
- if isinstance(val, string_types):
+ if isinstance(val, text_type):
return val.lower()
return val