使用Python从Gmail下载特定的电子邮件 [英] Download a specific email from Gmail using Python

查看:112
本文介绍了使用Python从Gmail下载特定的电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can someone help me customize an existing code sample?

从下面的文章中我可以看到如何连接到gmail并下载内容,但是我不知道如何搜索特定的电子邮件,而仅下载时间戳和正文?

I can see from the following article how to connect to gmail and download content, but I can't figure out how to search for a specific email and only download the timestamp and body?

文章:如何下载带有以下内容的所有电子邮件来自Gmail的附件?

我特别想在最近5天中从"Alerts@foobank.com"中获取电子邮件,然后下载电子邮件的发送时间和正文.然后,我将对此进行解析,以确定我需要使用哪些电子邮件.

I specifically want to grab the emails from "Alerts@foobank.com" for the last 5 days and download the send time and body of the emails. I'll then parse this to determine which emails I need to use.

我是自学成才,很难自定义上面的脚本来做到这一点.

I'm self-taught and am having a hard time customizing the script above to do this.

我们非常感谢您的帮助.谢谢.

Any help is much appreciated. Thanks.

JD

推荐答案

我建议在撰写本文时使用 IMAPClient 在IMAP的许多更深奥的方面.

I suggest using IMAPClient as it papers over many of the more esoteric aspects of IMAP.

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

The following snippet will pull messages based on your criteria, parse the message strings to email.message.Message instances and print the Date and From headers.

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'])

这篇关于使用Python从Gmail下载特定的电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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