如何从电子邮件中获取 csv 附件并保存

Posted

技术标签:

【中文标题】如何从电子邮件中获取 csv 附件并保存【英文标题】:How to get csv attachment from email and save it 【发布时间】:2013-09-01 02:05:33 【问题描述】:

我正在尝试从电子邮件中获取附件并将​​其保存到具有原始文件名的特定文件夹中。电子邮件非常基本,除了附件之外没有太多内容。该文件是一个 csv 文件,每封电子邮件只有一个。这是我到目前为止所拥有的,但我是新手,不知道如何继续。如果有帮助,这是使用 Outlook。任何帮助表示赞赏。

import imaplib
import email


mail=imaplib.IMAP4('mailserver.com')
mail.login("username", "password")
mail.select("DetReport")

typ, msgs = mail.uid('Search', None, '(SUBJECT "Detection")')
msgs = msgs[0].split()

for emailid in msgs:
    resp, data = mail.fetch(emailid, "(RFC822)")
    email_body = data[0][1] 
    m = email.message_from_string(email_body)


    message=m.get_content_maintype()

仅供参考,当我运行 message=m.get_content_maintype() 时,它说它是文本。

【问题讨论】:

【参考方案1】:

我又环顾四周,又尝试了一些东西。这些: Downloading multiple attachments using imaplib 和How do I download only unread attachments from a specific gmail label? 玩了一下就得到了答案。

有效的代码:

import imaplib
import email
import os

svdir = 'c:/downloads'


mail=imaplib.IMAP4('mailserver')
mail.login("username","password")
mail.select("DetReport")

typ, msgs = mail.search(None, '(SUBJECT "Detection")')
msgs = msgs[0].split()

for emailid in msgs:
    resp, data = mail.fetch(emailid, "(RFC822)")
    email_body = data[0][1] 
    m = email.message_from_string(email_body)


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

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

        filename=part.get_filename()
        if filename is not None:
            sv_path = os.path.join(svdir, filename)
            if not os.path.isfile(sv_path):
                print sv_path       
                fp = open(sv_path, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()

POP3:

import poplib
import email

server = poplib.POP3(pop_server)
server.user(user)
server.pass_(pass)

# get amount of new mails and get the emails for them
messages = [server.retr(n+1) for n in range(len(server.list()[1]))]

# for every message get the second item (the message itself) and convert it to a string with \n; then create python email with the strings
emails = [email.message_from_string('\n'.join(message[1])) for message in messages]

for mail in emails:
    # check for attachment;
    for part in mail.walk():
        if not mail.is_multipart():
            continue
        if mail.get('Content-Disposition'):
            continue
        file_name = part.get_filename()
        # check if email park has filename --> attachment part
        if file_name:
            file = open(file_name,'w+')
            file.write(part.get_payload(decode=True))
            file.close()

【讨论】:

以上是关于如何从电子邮件中获取 csv 附件并保存的主要内容,如果未能解决你的问题,请参考以下文章

android导出到csv并作为电子邮件附件发送

从 html 表单发送带有 csv 附件的电子邮件

使用PHP阅读电子邮件附件(csv)

使用 PHP 读取二进制电子邮件附件 (CSV)

在 python 中解析多部分电子邮件并保存附件

Zend Framework:如何阅读电子邮件附件(并保存到磁盘)?