使用Python从Gmail下载特定电子邮件

时间:2011-07-07 22:54:21

标签: python gmail imap

有人可以帮我自定义现有代码示例吗?

我可以从以下文章中看到如何连接到Gmail和下载内容,但我无法弄清楚如何搜索特定的电子邮件并只下载时间戳和正文?

文章:How can I download all emails with attachments from Gmail?

我特别想在过去5天内收到“Alerts@foobank.com”的电子邮件,并下载发送时间和电子邮件正文。然后我将解析这个以确定我需要使用哪些电子邮件。

我是自学成才,并且很难自定义上面的脚本来执行此操作。

非常感谢任何帮助。感谢。

JD

3 个答案:

答案 0 :(得分:18)

我建议使用IMAPClient作为IMAP许多更深奥的方面的论文。

以下代码段将根据您的条件提取邮件,将邮件字符串解析为email.message.Message个实例,并打印DateFrom标题。

from datetime import datetime, timedelta
import email
from imapclient import IMAPClient

HOST = 'imap.gmail.com'
USERNAME = 'username'
PASSWORD = 'password'
ssl = True

today = datetime.today()
cutoff = today - timedelta(days=5)

## Connect, login and select the INBOX
server = IMAPClient(HOST, use_uid=True, ssl=ssl)
server.login(USERNAME, PASSWORD)
select_info = server.select_folder('INBOX')

## Search for relevant messages
## see http://tools.ietf.org/html/rfc3501#section-6.4.5
messages = server.search(
    ['FROM "Alerts@foobank.com"', 'SINCE %s' % cutoff.strftime('%d-%b-%Y')])
response = server.fetch(messages, ['RFC822'])

for msgid, data in response.iteritems():
    msg_string = data['RFC822']
    msg = email.message_from_string(msg_string)
    print 'ID %d: From: %s Date: %s' % (msgid, msg['From'], msg['date'])

答案 1 :(得分:2)

import imaplib
from datetime import datetime, timedelta

obj = imaplib.IMAP4_SSL('imap.gmail.com',993)
obj.login('username','password')
obj.select()

today = datetime.today()
cutoff = today - timedelta(days=5)
dt = cutoff.strftime('%d-%b-%Y')
typ, data = obj.search(None, '(SINCE %s) (FROM "Alerts@foobank.com")'%(dt,))
print data

答案 2 :(得分:1)

import datetime as dt
from imap_tools import MailBox, Q
date = dt.date.today() - dt.timedelta(days=5)
with MailBox('imap.mail.com').login('test@mail.com', 'password', 'INBOX') as mailbox:
    for msg in mailbox.fetch(Q(from_='Alerts@foobank.com', date_gte=date)):
        sent_time = msg.date
        body = msg.text or msg.html
        for att in msg.attachments:
            att.filename         # str: 'cat.jpg'
            att.content_type     # str: 'image/jpeg'
            att.payload          # bytes: b'\xff\xd8\xff\xe0\'

*请注意,没有“带有附件”的imap搜索条件

https://github.com/ikvk/imap_tools