有人可以帮我定制现有的代码示例吗?
我可以从下面的文章中看到如何连接到gmail并下载内容,但我不知道如何搜索特定电子邮件并仅下载时间戳和正文?
文章:如何从 Gmail 下载所有带附件的电子邮件? https://stackoverflow.com/questions/348630/how-can-i-download-all-emails-with-attachments-from-gmail
我特别想抓取来自“[电子邮件受保护] /cdn-cgi/l/email-protection“过去 5 天并下载电子邮件的发送时间和正文。然后我将对其进行解析以确定我需要使用哪些电子邮件。
我是自学成才的,很难自定义上面的脚本来做到这一点。
任何帮助深表感谢。谢谢。
JD
我建议使用IMAP客户端 http://imapclient.freshfoo.com/因为它涵盖了 IMAP 的许多深奥的方面。
以下代码片段将根据您的条件提取消息,将消息字符串解析为email.message.Message http://docs.python.org/library/email.message.html#email.message.Message实例并打印Date
and From
标头。
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 "[email protected] /cdn-cgi/l/email-protection"', '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'])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)