"TypeError: can't concat int to bytes" imaplib error

"TypeError: can't concat int to bytes" imaplib error

我正在创建一些东西,所以当它根据主题行收到一封电子邮件时,它会起作用,现在我的代码在 python 2.7 中工作并在 3.7 中运行,但给出一个错误“TypeError:无法将 int 连接到字节”我没有尝试太多,因为我在网上找不到任何东西而且我是 python 的新手,请告诉我

import imaplib
import email
from time import sleep
from ssh import myRoomOff, myRoomOn

count = 0 

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('EMAIL', 'PASSWORD')
mail.list()
mail.select('inbox')

#need to add some stuff in here
while True:
    mail.select('inbox')
    typ, data = mail.search(None, 'UNSEEN')
    ids = data[0]
    id_list = ids.split()


    #get the most recent email id
    latest_email_id = int( id_list[-1] )

    #iterate through 15 messages in decending order starting with latest_email_id
    #the '-1' dictates reverse looping order
    for i in range( latest_email_id, latest_email_id-1, -1 ):
        typ, data = mail.fetch(i, '(RFC822)' )

    for response_part in data:
        if isinstance(response_part, tuple):
            msg = email.message_from_bytes(response_part[1])
            varSubject = msg['subject']

            count += 1
            print(str(count) + ", " + varSubject)
            if varSubject == "+myRoom":
                myRoomOn()
            elif varSubject == "-myRoom":
                myRoomOff()
            else:
                print("I do not understand this email!")
                pass
    sleep(2)

错误

Traceback (most recent call last):
  File "/Users/danielcaminero/Desktop/alexaCommandThing/checkForEmail.py", line 28, in <module>
    typ, data = mail.fetch(i, '(RFC822)' )
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/imaplib.py", line 548, in fetch
    typ, dat = self._simple_command(name, message_set, message_parts)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/imaplib.py", line 1230, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/imaplib.py", line 988, in _command
    data = data + b' ' + arg
TypeError: can't concat int to bytes

mail.fetch() 的第一个参数必须是字符串,但 range() 产生一个 int。 所以字符串转换会修复它:

typ, data = mail.fetch(str(i), '(RFC822)')

修复它不是必要的更改,但反转列表的更 pythonic 方法是使用列表切片 [::-1]。您可以保存一些行和 range() 调用。
此外你的缩进是错误的,你只处理最后一次迭代的数据。

...
id_list = ids.split()

for i in id_list[::-1]:
    typ, data = mail.fetch(i, '(RFC822)')
    for response_part in data:
        if isinstance(response_part, tuple):
            msg = email.message_from_bytes(response_part[1])
            varSubject = msg['subject']

            count += 1
            print(str(count) + ", " + varSubject)
            if varSubject == "+myRoom":
                myRoomOn()
            elif varSubject == "-myRoom":
                myRoomOff()
            else:
                print("I do not understand this email!")
                pass

(这里不需要字符串转换,因为 id_list 是一个字节串列表。字节串也是 fetch() 的有效值。)