使用imaplib下载多个附件

har*_*rde 23 python email imap attachment

如何使用imaplib从单个邮件下载多个附件?

假设我有一封电子邮件,该电子邮件包含4个附件.如何下载所有这些附件?以下代码仅从电子邮件中下载单个附件.

detach_dir = 'c:/downloads'
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login('hello@gmail.com','3323434')
m.select("[Gmail]/All Mail")

resp, items = m.search(None, "(UNSEEN)")
items = items[0].split()

for emailid in items:
    resp, data = m.fetch(emailid, "(RFC822)") 
    email_body = data[0][1] 
    mail = email.message_from_string(email_body) 
    temp = m.store(emailid,'+FLAGS', '\\Seen')
    m.expunge()

    if mail.get_content_maintype() != 'multipart':
        continue

    print "["+mail["From"]+"] :" + mail["Subject"]

    for part in mail.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue

        filename = part.get_filename()
        att_path = os.path.join(detach_dir, filename)

        if not os.path.isfile(att_path) :
            fp = open(att_path, 'wb')
            fp.write(part.get_payload(decode=True))
            fp.close()
            return HttpResponse('check folder')
Run Code Online (Sandbox Code Playgroud)

Joh*_*yes 35

对于任何未来的蟒蛇旅行者.这是一个下载为电子邮件找到的任何附件并将其保存到特定位置的类.

import email
import imaplib
import os

class FetchEmail():

    connection = None
    error = None

    def __init__(self, mail_server, username, password):
        self.connection = imaplib.IMAP4_SSL(mail_server)
        self.connection.login(username, password)
        self.connection.select(readonly=False) # so we can mark mails as read

    def close_connection(self):
        """
        Close the connection to the IMAP server
        """
        self.connection.close()

    def save_attachment(self, msg, download_folder="/tmp"):
        """
        Given a message, save its attachments to the specified
        download folder (default is /tmp)

        return: file path to attachment
        """
        att_path = "No attachment found."
        for part in msg.walk():
            if part.get_content_maintype() == 'multipart':
                continue
            if part.get('Content-Disposition') is None:
                continue

            filename = part.get_filename()
            att_path = os.path.join(download_folder, filename)

            if not os.path.isfile(att_path):
                fp = open(att_path, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()
        return att_path

    def fetch_unread_messages(self):
        """
        Retrieve unread messages
        """
        emails = []
        (result, messages) = self.connection.search(None, 'UnSeen')
        if result == "OK":
            for message in messages[0].split(' '):
                try: 
                    ret, data = self.connection.fetch(message,'(RFC822)')
                except:
                    print "No new emails to read."
                    self.close_connection()
                    exit()

                msg = email.message_from_bytes(data[0][1])
                if isinstance(msg, str) == False:
                    emails.append(msg)
                response, data = self.connection.store(message, '+FLAGS','\\Seen')

            return emails

        self.error = "Failed to retreive emails."
        return emails

    def parse_email_address(self, email_address):
        """
        Helper function to parse out the email address from the message

        return: tuple (name, address). Eg. ('John Doe', 'jdoe@example.com')
        """
        return email.utils.parseaddr(email_address)
Run Code Online (Sandbox Code Playgroud)

  • 对于Python 3,请使用“ msg = email.message_from_bytes(data [0] [1])”代替“ msg = email.message_from_string(data [0] [1])”。否则,msg.walk()中的一部分将无法正常工作。 (3认同)
  • 我建议你像下面这样做。它更简单,并且适用于八位字节流附件。filename = part.get_filename() if filename: att_path = os.path.join(download_folder, filename) fp = open(att_path, 'wb') fp.write(part.get_payload(decode=True)) fp.close() (2认同)

sas*_*alm 12

我重新编写了代码,将其分解为函数.我使用PEEK所以我不会更改电子邮件的UNREAD状态.

我发布了对问题的看法,类似于@John,但我只使用函数而不是类:

import imaplib
import email

# Connect to an IMAP server
def connect(server, user, password):
    m = imaplib.IMAP4_SSL(server)
    m.login(user, password)
    m.select()
    return m

# Download all attachment files for a given email
def downloaAttachmentsInEmail(m, emailid, outputdir):
    resp, data = m.fetch(emailid, "(BODY.PEEK[])")
    email_body = data[0][1]
    mail = email.message_from_string(email_body)
    if mail.get_content_maintype() != 'multipart':
        return
    for part in mail.walk():
        if part.get_content_maintype() != 'multipart' and part.get('Content-Disposition') is not None:
            open(outputdir + '/' + part.get_filename(), 'wb').write(part.get_payload(decode=True))

# Download all the attachment files for all emails in the inbox.
def downloadAllAttachmentsInInbox(server, user, password, outputdir):
    m = connect(server, user, password)
    resp, items = m.search(None, "(ALL)")
    items = items[0].split()
    for emailid in items:
        downloaAttachmentsInEmail(m, emailid, outputdir)
Run Code Online (Sandbox Code Playgroud)

  • 对于“emailid”,查看“downloadAllAttachmentsInInbox()”如何调用“downloaAttachmentsInEmail()”。对于outputdir,它是下载附件的目录。 (2认同)
  • 这个确实有效。就我而言,我必须将 message_from_string 更改为 message_from_bytes 并且它工作得很好。 (2认同)

sam*_*ias 6

您的代码看起来没问题,除了return(可能是错字?)之后fp.close():

...
fp.write(part.get_payload(decode=True))
fp.close()
return HttpResponse('check folder')
Run Code Online (Sandbox Code Playgroud)

保存第一个附件后,它将从函数返回.注释掉该行,看看它是否解决了您的问题.


Vla*_*mir 5

您可以使用 imap_tools 包: https: //pypi.org/project/imap-tools/

from imap_tools import MailBox
with MailBox('imap.mail.com').login('test@mail.com', 'password', 'INBOX') as mailbox:
    for message in mailbox.fetch():
        for att in message.attachments:  # list: [Attachment objects]
            att.filename         # str: 'cat.jpg'
            att.content_type     # str: 'image/jpeg'
            att.payload          # bytes: b'\xff\xd8\xff\xe0\'
Run Code Online (Sandbox Code Playgroud)