0

I want to only print the sender name and message of a received gmail in Python. I tried the code given below. Please help me with that.

import imaplib

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('raskarakash2017@gmail.com', '02426236032')
mail.list()
mail.select('inbox')

typ, data = mail.search(None, 'ALL')
for num in data[0].split():
   typ, data = mail.fetch(num, '(RFC822)')
   print ('Message %s\n%s\n' % (num, data[0][1]))
mail.close()


mail.logout()

This code prints the whole information of the gmail, but I don't need that.

Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38
  • Hope this will help https://stackoverflow.com/questions/7314942/python-imaplib-to-get-gmail-inbox-subjects-titles-and-sender-name – Akhilraj N S Jun 25 '19 at 06:37

1 Answers1

1

I think you are looking for it:

import imaplib
import email

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('raskarakash2017@gmail.com', '02426236032')
mail.list()
mail.select('inbox')

typ, data = mail.search(None, 'ALL')
for num in data[0].split():
   typ, data = mail.fetch(num, '(RFC822)')
   for response_part in data:
      if isinstance(response_part, tuple):
          msg = email.message_from_string(response_part[1])
          varSubject = msg['subject']
          varFrom = msg['from']

   #remove the brackets around the sender email address
   varFrom = varFrom.replace('<', '')
   varFrom = varFrom.replace('>', '')

   #add ellipsis (...) if subject length is greater than 35 characters
   if len( varSubject ) > 35:
      varSubject = varSubject[0:32] + '...'

   print '[' + varFrom.split()[-1] + '] ' + varSubject
mail.close()
mail.logout()

Details are here : link

mahbubcseju
  • 2,200
  • 2
  • 16
  • 21