4

how do i read mails from my mail box using python??

import getpass, imaplib
M = imaplib.IMAP4('IMAP4.gmail.com:993')
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()

this is my code.. but when i execute this its throwing error:

Traceback (most recent call last):
  File "E:/jagdish/python progs/readmail.py", line 2, in <module>
    M = imaplib.IMAP4('IMAP4.gmail.com:993')
  File "C:\Python25\lib\imaplib.py", line 163, in __init__
    self.open(host, port)
  File "C:\Python25\lib\imaplib.py", line 230, in open
    self.sock.connect((host, port))
  File "<string>", line 1, in connect
gaierror: (11001, 'getaddrinfo failed')

can anyone help me with this???

2 Answers 2

13

Three issues:

  1. The hostname is imap.gmail.com, not imap4.gmail.com
  2. The IMAP4 constructor takes two parameters: the host and port (not colon-separated)
  3. Gmail expects you to be talking SSL

So:

import imaplib
M = imaplib.IMAP4_SSL("imap.gmail.com", 993)
Sign up to request clarification or add additional context in comments.

2 Comments

This is the answer: Gmail expects you to be talking SSL. Use the IMAP4_SSL() function like SimonJ says. I've done this with GMail using POP3 recently. IMAP should be the same.
As the default ssl port is 993, you can write it as: M = imaplib.IMAP4_SSL("imap.gmail.com")
1

The error means that the host is unreachable or does not exist, which you could find out by googling for 'gaierror' (it stands for get address info error).

Try "imap.gmail.com:993" instead, as described here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.