python imaplib获取gmail收件箱主题标题和发件人姓名 [英] python imaplib to get gmail inbox subjects titles and sender name

查看:633
本文介绍了python imaplib获取gmail收件箱主题标题和发件人姓名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用pythons imaplib连接到我的Gmail帐户。我想检索前15个邮件(未读或读取,没关系),只显示主题和发件人姓名(或地址),但不知道如何显示收件箱的内容。



到目前为止,我的代码(成功连接)

  import imaplib 

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

#需要在这里添加一些东西

mail.logout()

我相信这应该很简单,我对imaplib库的命令不够熟悉。任何帮助将不胜感激......



更新
感谢Julian我可以迭代每条消息并检索整个内容与:

  typ,data = mail.search(无,'ALL')
用于数据中的num [0 ] .split():
typ,data = mail.fetch(num,'(RFC822)')
print'Message%s\%%s\\\
'%(num,data [ 0] [1])$ ​​b $ b mail.close()

但我只想要主题和发件人。是否有这些项目的imaplib命令,或者我将不得不解析文本的全部内容[0] [1]:主题和发件人?

UPDATE
OK,获得主题和发件人部分工作,但迭代(1,15)通过desc顺序完成,显然向我显示最早的消息。我该如何改变这一点?我尝试这样做:

 对于范围内的len(len(data [0]) -  15,len(data [0] )):
打印数据

但这只是给我 None 对于所有15次迭代...任何想法?我也试过 mail.sort('REVERSE DATE','UTF-8','ALL')但gmail不支持.sort()函数



更新
想出了一个办法:

 #.... ^除需要导入电子邮件模块外,其他代码与上述内容相同
mail.select('inbox')
typ,data = mail.search(None ,'ALL')
ids = data [0]
id_list = ids.split()
#获取最近的电子邮件ID
latest_email_id = int(id_list [-1] )

#iterate通过15条消息以递减顺序开始latest_email_id
#'-1'指示反向循环顺序
为范围内的i(latest_email_id,latest_email_id-15, - 1):
typ,data = mail.fetch(i,'(RFC822)')

for response_part in data:
if isinstance(response_part,tuple):
msg = email.message_from_string(response_part [1])$ ​​b $ b varSubject = msg ['subject']
varFrom = msg ['from ]

#移除发件人电子邮件地址的括号
varFrom = varFrom.replace('<','')
varFrom = varFrom.replace('>' ,'')

#add省略号(...)如果主题长度大于35个字符
if len(varSubject)> 35:
varSubject = varSubject [0:32] +'...'

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

这给了我最近的15个消息主题和发件人地址,按照要求降序排列!感谢所有的帮助!

解决方案

  c.select('INBOX',readonly = True)

(1,30):
typ,msg_data = c.fetch(str(i),'(RFC822)')
for response_part in msg_data:
如果isinstance(response_part,tuple):
msg = email.message_from_string(response_part [1])$ ​​b $ b用于['subject','to','from']中的标题:
print'%-8s:%s'%(header.upper(),msg [header])

这应该给你一个关于如何检索主题和来自?
的想法

I'm using pythons imaplib to connect to my gmail account. I want to retrieve the top 15 messages (unread or read, it doesn't matter) and display just the subjects and sender name (or address) but don't know how to display the contents of the inbox.

Here is my code so far (successful connection)

import imaplib

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

#need to add some stuff in here

mail.logout()

I believe this should be simple enough, I'm just not familiar enough with the commands for the imaplib library. Any help would be must appreciated...

UPDATE thanks to Julian I can iterate through each message and retrieve the entire contents with:

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

but I'm wanting just the subject and the sender. Is there a imaplib command for these items or will I have to parse the entire contents of data[0][1] for the text: Subject, and Sender?

UPDATE OK, got the subject and sender part working but the iteration (1, 15) is done by desc order apparently showing me the oldest messages first. How can I change this? I tried doing this:

for i in range( len(data[0])-15, len(data[0]) ):
     print data

but that just gives me None for all 15 iterations... any ideas? I've also tried mail.sort('REVERSE DATE', 'UTF-8', 'ALL') but gmail doesnt support the .sort() function

UPDATE Figured out a way to do it:

#....^other code is the same as above except need to import email module
mail.select('inbox')
typ, data = mail.search(None, 'ALL')
ids = data[0]
id_list = ids.split()
#get the most recent email id
latest_email_id = int( id_list[-1] )

#iterate through 15 messages in decending order starting with latest_email_id
#the '-1' dictates reverse looping order
for i in range( latest_email_id, latest_email_id-15, -1 ):
   typ, data = mail.fetch( i, '(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

this gives me the most recent 15 message subject and sender address in decending order as requested! Thanks to all who helped!

解决方案

    c.select('INBOX', readonly=True)

    for i in range(1, 30):
        typ, msg_data = c.fetch(str(i), '(RFC822)')
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                msg = email.message_from_string(response_part[1])
                for header in [ 'subject', 'to', 'from' ]:
                    print '%-8s: %s' % (header.upper(), msg[header])

This should give you an idea on how to retrieve the subject and from?

这篇关于python imaplib获取gmail收件箱主题标题和发件人姓名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆