所以我是编码的初学者,因此我选择了Python作为入门。我正在尝试整理一个脚本,以获取从特定联系人收到的最后一封电子邮件的“日期”。然后,此“日期”将保存在Google工作表中。
下面是我到目前为止拥有的仅处理Gmail部分的代码。我实际上已经使用了here中的部分代码。但是,我得到一个错误
追踪(最近通话):文件“ C:/Users/PycharmProjects/Automate/Code.py”,第33行,在msg_string =数据['RFC822']KeyError:“ RFC822”
不知道怎么了。我正在使用Python 3.8.1
import email
from imapclient import IMAPClient
HOST = 'imap.gmail.com'
USERNAME = 'username'
PASSWORD = 'password'
ssl = True
## Connect, login and select the INBOX
server = IMAPClient(HOST, use_uid=True, ssl=ssl)
server.login(USERNAME, PASSWORD)
select_info = server.select_folder('INBOX')
messages = server.search(['FROM', '[email protected]'])
response = server.fetch(messages, ['RFC822'])
for msgid, data in response.items():
msg_string = data['RFC822']
msg = email.message_from_string(msg_string)
print('ID %d: From: %s Date: %s' % (msgid, msg['From'], msg['date']))
同样,我不确定要完成的代码是否完整。任何帮助表示赞赏。
此外,添加从调试获得的消息
pydev debugger: process 344 is connecting
Connected to pydev debugger (build 193.6494.30)
Traceback (most recent call last):
File "C:\Users\PycharmProjects\Automate\venv\lib\site-packages\httplib2\__init__.py", line 1557, in _conn_request
conn.connect()
File "C:\Users\PycharmProjects\Automate\venv\lib\site-packages\httplib2\__init__.py", line 1305, in connect
address_info = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
File "C:\Program Files (x86)\Python38-32\lib\socket.py", line 918, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\PycharmProjects\Automate\venv\lib\site-packages\httplib2\__init__.py", line 1982, in request
(response, content) = self._request(
File "C:\Users\PycharmProjects\Automate\venv\lib\site-packages\httplib2\__init__.py", line 1650, in _request
(response, content) = self._conn_request(
File "C:\Users\PycharmProjects\Automate\venv\lib\site-packages\httplib2\__init__.py", line 1564, in _conn_request
raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
httplib2.ServerNotFoundError: Unable to find the server at oauth2.googleapis.com
Process finished with exit code -1
在这里,我遍历了您的代码以再次产生相同的错误,并且得到相同的结果。
为了解决这个问题,我检查了字典键,并注意到字典键和值被编码为字节。
所以,我使用字节键访问和解码以将消息转换为str,如下:
import email
from imapclient import IMAPClient
HOST = 'imap.gmail.com'
USERNAME = 'username'
PASSWORD = 'password'
ssl = True
## Connect, login and select the INBOX
server = IMAPClient(HOST, use_uid=True, ssl=ssl)
server.login(USERNAME, PASSWORD)
select_info = server.select_folder('INBOX')
messages = server.search(['FROM', '[email protected]'])
response = server.fetch(messages, ['RFC822'])
for msgid, data in response.items():
msg_string = data[b'RFC822']
msg = email.message_from_string(msg_string.decode())
print('ID %d: From: %s Date: %s' % (msgid, msg['From'], msg['date']))