1

So I am a beginner in coding and I have chosen Python to get started. I am trying to put together a script to get the "date" of the last email received from a particular contact. This "date" will be then saved in the Google sheet.

Below is the code that I have so far which deals with just the Gmail part. I have actually used part of the code from here. However, I am getting an error

Traceback (most recent call last): File "C:/Users/PycharmProjects/Automate/Code.py", line 33, in msg_string = data['RFC822'] KeyError: 'RFC822'

Not sure what's going wrong. I am using 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_of_the_contact@gmail.com'])

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']))

Also, not sure if the code is complete in terms of what I am trying to achieve. Any help appreciated.

Also, adding in the message got from debug

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
Vin.AI
  • 2,369
  • 2
  • 19
  • 40
  • To debug it print response and check what is really in it, and add the information to the question. – Artiom Kozyrev Mar 05 '20 at 08:51
  • Dictionary keys are in byte coded not string, Replace `msg_string = data['RFC822']` to `msg_string = data[b'RFC822']`. Mind the **b** – Vin.AI Mar 05 '20 at 09:00
  • @ArtiomKozyrev I added in the debug response to the question. – Sourav Chatterjee Mar 05 '20 at 09:03
  • @Vin.AI I added in and its giving me this error Traceback (most recent call last): File "C:/Users/PycharmProjects/Automate/RelDash-Code.py", line 34, in msg = email.message_from_string(msg_string) File "C:\Program Files (x86)\Python38-32\lib\email\__init__.py", line 38, in message_from_string return Parser(*args, **kws).parsestr(s) File "C:\Program Files (x86)\Python38-32\lib\email\parser.py", line 67, in parsestr return self.parse(StringIO(text), headersonly=headersonly) TypeError: initial_value must be str or None, not bytes – Sourav Chatterjee Mar 05 '20 at 09:08
  • I've submitted answer below. For the same issue – Vin.AI Mar 05 '20 at 09:09

1 Answers1

2

Here I ran through your code to re-produce the same error and I got the same.

To rid the problem, I checked the dict keys and noticed that dict keys and values are encoded as byte.

So, I used byte key to access and decode to translate message to str, as:

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_of_the_contact@gmail.com'])

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']))
Vin.AI
  • 2,369
  • 2
  • 19
  • 40