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

发布于 2024-11-18 18:42:54 字数 501 浏览 1 评论 0 原文

有人可以帮我定制现有的代码示例吗?

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

文章:如何从 Gmail 下载所有带附件的电子邮件?

我特别想从“[电子邮件受保护]" 并下载电子邮件的发送时间和正文。然后我将解析它以确定我需要使用哪些电子邮件。

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

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

京东

Can someone help me customize an existing code sample?

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?

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

I specifically want to grab the emails from "[email protected]" 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

淡淡離愁欲言轉身 2024-11-25 18:42:55

我建议使用 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 "[email protected]"', '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'])

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

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 "[email protected]"', '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'])
耀眼的星火 2024-11-25 18:42:55
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 "[email protected]")'%(dt,))
print data
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 "[email protected]")'%(dt,))
print data
软糯酥胸 2024-11-25 18:42:55
import datetime as dt
from imap_tools import MailBox, Q
date = dt.date.today() - dt.timedelta(days=5)
with MailBox('imap.mail.com').login('[email protected]', 'password', 'INBOX') as mailbox:
    for msg in mailbox.fetch(Q(from_='[email protected]', 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

import datetime as dt
from imap_tools import MailBox, Q
date = dt.date.today() - dt.timedelta(days=5)
with MailBox('imap.mail.com').login('[email protected]', 'password', 'INBOX') as mailbox:
    for msg in mailbox.fetch(Q(from_='[email protected]', 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\'

*Note that there is no imap search criteria "with attachments"

https://github.com/ikvk/imap_tools

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文