“TypeError: can't concat int to bytes” imaplib 错误

问题描述

我正在创建一些东西,所以当它收到一封电子邮件时,它会根据主题行执行一个功能,现在我的代码在 python 2.7 中运行并在 3.7 中运行,但给出了一个错误“TypeError: can't concat int to字节”我还没有尝试太多,因为我在网上找不到任何东西,而且我是 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,'(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() 的有效值。)