0
import imaplib
import email
import socket

socket.getaddrinfo('127.0.0.1', 8080)


def read_email_from_gmail():
    try:
        mail = imaplib.IMAP4_SSL('imap.gmail.com', 993)
        mail.login('your email', 'your password')
        mail.select('inbox')

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

        id_list = mail_ids.split()

        typ, data = mail.fetch(bytes(str(id_list), 'utf-8'), '(RFC822)')

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

    except Exception as e:
        print(str(e))


read_email_from_gmail()


Output: FETCH command error: BAD [b'Could not parse command']

I want to receive a mail from Gmail using Python. Could someone help me where I'm going wrong? and what is this error?

Thank you in advance!

  • Please do not change your question after posting. Also, try turning not he imaplib debug and trace facilities. Also, start by fetching *one* message at a time, by using a for loop over id_list, rather than trying to fetch them all at once. fetch() does not take a python list, and just forcing it into 'bytes' doesn't make it acceptable to the server. – Max Jun 07 '20 at 14:07

1 Answers1

0

I think you have the name of the server wrong. It should be imap.gmail.com.

Here's how I figured that out. I did a search for 11001 and getaddrinfo and learned that this error code was from Windows saying the host was not found.

I tried to ping imap.google.com and the hostname could not be resolved.

I did a search for "google imap server" and found a different hostname in Google's documentation.

Dennis Sparrow
  • 938
  • 6
  • 13
  • Thank you! I got it! but, there's nothing printing in my output once I resolve the mistake you told me. Can you see where I'm going wrong? – Ram nishanth Jun 07 '20 at 08:04
  • I don't know if this is the problem, but you are using the port number for the SMTP server. – Dennis Sparrow Jun 07 '20 at 08:08
  • 1
    When you change the title of the question and fix the code in it, you make it less useful to future readers with the same problem. I suggest you restore the original code and title and post your current issue as a separate question. It's not something I can easily answer, anyway. – Dennis Sparrow Jun 07 '20 at 08:34