Search code examples
pythonimap

Python 3 imaplib.fetch TypeError: can't concat bytes to int


I have some code which fetches IMAP emails and works completely well in Python 2. In Python3 I get the following error:

Traceback (most recent call last):
File "./mail.py", line 295, in
item=return_message(x)
File "./mail.py", line 122, in return_message
result, data = mail.fetch(message_id, "(RFC822)")
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/imaplib.py", line 460, in fetch
typ, dat = self._simple_command(name, message_set, message_parts)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/imaplib.py", line 1113, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/imaplib.py", line 883, in _command
data = data + b' ' + arg
TypeError: can't concat bytes to int

The code from the return_message function:

result, data = mail.fetch(message_id, "(RFC822)")
raw_email = data[0][1]
email_message = email.message_from_string(raw_email)

Runtime Information:

3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 01:25:11)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]


Solution

  • message_set is a string, not an int. From the documentation:

    The message_set options to commands below is a string specifying one or more messages to be acted upon. It may be a simple message number ('1'), a range of message numbers ('2:4'), or a group of non-contiguous ranges separated by commas ('1:3,6:9'). A range can contain an asterisk to indicate an infinite upper bound ('3:*').

    Converting it to string directly should be enough:

    result, data = mail.fetch(str(message_id), "(RFC822)")