阅读gmail并进行打印

时间:2019-06-25 04:46:29

标签: python python-3.x imaplib

我只想在Python中打印发件人名称和收到的gmail消息。我尝试了下面给出的代码。请帮我。

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()

此代码可打印gmail的全部信息,但我不需要。

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找它:

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()

详细信息在这里:link