使用python的IMAP下载附件 [英] IMAP with python to download attachments
问题描述
我有一个工作工具,可以通过电子邮件将包含原始数据的文件发送给我,我可以进入我的电子邮件并轻松下载它们,但是当我有多个文件(作为多个电子邮件发送)时,它会变得有些乏味。
I have a instrument at work that emails me a file containing raw data, I can go into my email and download them easily enough but when I have multiple files (which it sends as multiple emails) it gets a bit tedious.
我正在使用 python
和 imaplib
要登录到我的电子邮件帐户,请在过去一天左右的时间内从已知电子邮件地址中搜索电子邮件,然后将所有附件下载到目录中。因此,我认为脚本可能会有所帮助。
I'm looking at using python
and imaplib
to login to my email account, search for emails from a known email address within the past day or so and then download any attachments to a directory. So I thought a script might help here.
我已经设置了一个gmail帐户并更改了设置,以便可以从外壳程序使用imap进行连接,但是我不知道该从何处去。
I've setup a gmail account and altered the settings so that I can connect using imap from a shell, however I'm lost as to where to go from here.
有人可以为我指出正确的方向以实现这一目标。
Could someone point me in the right direction as to what I need to do to make this happen.
推荐答案
这里是从imaplib分叉的存储库(与Python3.6兼容,未测试其他版本)
Here is a repository that is forked off imaplib (made compatible with Python3.6, did not test other versions)
https://github.com/christianwengert/mail
https://github.com/christianwengert/mail
以下代码段检查所有看不见的邮件,然后返回其附件:
The following snippet checks all unseen messages, then returns their attachments:
server = IMAPClient(imap, use_uid=True, ssl=993)
server.login(username, password)
server.select_folder('INBOX')
message_ids = server.search([b'NOT', b'SEEN']) # UNSEEN
messages = server.fetch(message_ids, data=['ENVELOPE', 'BODYSTRUCTURE', 'RFC822.SIZE'])
for mid, content in messages.items():
bodystructure = content[b'BODYSTRUCTURE']
text, attachments = walk_parts(bodystructure, msgid=mid, server=server)
HTH
这篇关于使用python的IMAP下载附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!