简体   繁体   English

如何在 python imap 中获取 email 附件大小

[英]How to get email attachment size in python imap

How to get email attachment size in python imap如何在 python imap 中获取 email 附件大小

            # DOWNLOAD ATTACHMENTS
            for part in msg.walk():
                # this part comes from the snipped I don't understand yet... 
                if part.get_content_maintype() == 'multipart':
                    continue
                if part.get('Content-Disposition') is None:
                    continue
                fileName = part.get_filename()
                return HttpResponse(fileSize)
                if bool(fileName):
                    filePath = os.path.join('C:/Users/bali/attachments/', fileName)
                    if not os.path.isfile(filePath) :
                        fp = open(filePath, 'wb')
                        fp.write(part.get_payload(decode=True))
                        fp.close()

Is there any function to get size of the attachment just like "get_filename()" to get the name of the file.是否有任何 function 来获取附件的大小,就像“get_filename()”来获取文件名一样。

Well, you have the filename, so you can use os.path.getsize好吧,你有文件名,所以你可以使用os.path.getsize

import os
os.path.getsize(part.get_filename())

Information about the attachment size is not available in the header of the MIME message (you can check this by sending an attachment to yourself and seeing the original email to see if there is any information about attachment size) but you can get the size of the attachment without "creating a file", which I consider is equivalent to "downloading the attachment". MIME 消息的 header 中没有有关附件大小的信息(您可以通过向自己发送附件并查看原始 email 以查看是否有有关附件大小的任何信息来检查这一点),但您可以获得没有“创建文件”的附件,我认为这相当于“下载附件”。

You can do so by getting the payload of the part with attachment and then returning the length of the payload:您可以通过获取带有附件的部分的有效负载然后返回有效负载的长度来做到这一点:

payload = part.get_payload(decode=True)
file_size = len(payload) # in bytes

Also, instead of checking for part.get_filename() , as you did in your sample code, I recommend using is_attachment() check on the message part OR instead of walk() using iter_attachments() to get all the message parts with attachments.此外,我建议不要像在示例代码中那样检查part.get_filename() ,而是使用is_attachment()检查消息部分,或者使用iter_attachments()而不是walk() () 来获取所有带有附件的消息部分。 You can see how the attachments are handled in this python emails document examples .您可以在此python 电子邮件文档示例中查看如何处理附件。

You may try external lib: https://github.com/ikvk/imap_tools您可以尝试外部库: https://github.com/ikvk/imap_tools

from imap_tools import MailBox, A

with MailBox('imap.mail.com').login('test@mail.com', 'pwd', 'INBOX') as mailbox:
    for msg in mailbox.fetch(A(all=True)):
        print(msg.subject, msg.date)
        for att in msg.attachments:
            print(att.filename, att.size)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM