我如何才能使该python2函数读取在python3中运行的电子邮件?

时间:2018-09-01 13:10:36

标签: python python-3.x email

我一直在遵循有关如何使用python阅读电子邮件的指南

https://codehandbook.org/how-to-read-email-from-gmail-using-python/

import smtplib
import time
import imaplib
import email

ORG_EMAIL   = "@gmail.com"
FROM_EMAIL  = "mygmail" + ORG_EMAIL
FROM_PWD    = "mypassword"
SMTP_SERVER = "imap.gmail.com"
SMTP_PORT   = 993
def read_email_from_gmail():
    mail = imaplib.IMAP4_SSL(SMTP_SERVER)
    mail.login(FROM_EMAIL,FROM_PWD)
    mail.select('inbox')

    type, data = mail.search(None, 'ALL')
    mail_ids = data[0]

    id_list = mail_ids.split()   
    first_email_id = int(id_list[0])
    latest_email_id = int(id_list[-1])


    for i in range(latest_email_id,first_email_id, -1):
        typ, data = mail.fetch(i, '(RFC822)' )

        for response_part in data:
            if isinstance(response_part, tuple):
                msg = email.message_from_string(response_part[1])
                email_subject = msg['subject']
                email_from = msg['from']
                print('From : ' + email_from + '\n')
                print('Subject : ' + email_subject + '\n')

此代码是为python2编写的,可以在python2上运行,但效果很好,但是我想与python3一起使用,因此我尝试翻译该代码。首先,我将print foobar的所有实例更改为print(foobar)

但是我收到错误消息'TypeError:无法将字节连接为int'

Traceback (most recent call last):
  File "mymail.py", line 37, in <module>
    read_email_from_gmail()
  File "mymail.py", line 26, in read_email_from_gmail
    typ, data = mail.fetch(i, '(RFC822)' )
  File "/usr/lib/python3.5/imaplib.py", line 518, in fetch
    typ, dat = self._simple_command(name, message_set, message_parts)
  File "/usr/lib/python3.5/imaplib.py", line 1180, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "/usr/lib/python3.5/imaplib.py", line 945, in _command
    data = data + b' ' + arg
TypeError: can't concat bytes to int

我对这个错误不太熟悉。但是,使用python2中文本的原始代码可以完美地解决问题。我有点理解错误的意思,它不能将字节与数字连接在一起。但是我不确定为什么从python2到python3会发生此错误。

0 个答案:

没有答案