How To Get Emails Using Python And Imaplib

How To Get Emails Using Python And Imaplib

Below is the process of getting mails using python & imaplib Read on

 

1)connecting to mail server-

import imaplib

import email

imap_server = imaplib.IMAP4_SSL(“server_name”,port)

#Example:address of gmails imap server- imap.gmail.com:993

Imap_server.list() #this returns list of all labels/folders in email

imap_server.login(username, password)# if successful login will return (‘OK’, [‘Logged in’])

 

 

  • Fetching mails from server –

#Here we will be fetching unread mails.

Imap_server.select(“Inbox”)#we select from which folder/label we want to retrive mails

(status, messages) = Imap_server.search(None, ‘(UNSEEN)’)#this will search for all unseen mails.If user wants all mails set UNSEEN to ALL.

unreadcount = int(messages[0].split()[2].strip(‘).,]’))

print unreadcount

if status== ‘OK’:#check status

for num in messages[0].split(‘ ‘):

print ‘Processing :’, messages

typ, data = serv.fetch(num,'(RFC822)’)

msg = email.message_from_string(data[0][1])

if typ == ‘OK’:

print msg

serv.close()

Contact Us for Customized ERP Solutions