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

标签 python csv python-2.7 email-attachments imaplib

我正在尝试从电子邮件中获取附件并将​​其保存到具有原始文件名的特定文件夹中。该电子邮件非常基本,除了附件外没有太多内容。该文件是一个 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() 时,它说它是文本。

最佳答案

我又环顾四周,尝试了更多的东西。这些: Downloading multiple attachments using imaplibHow 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()

关于python - 如何从电子邮件中获取 csv 附件并保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18497397/

相关文章:

python - 使用继承编写 __repr__ 函数的正确方法

python - 如何编写一个 python 脚本,根据特定键合并两个 csv 文件中的列

Linux 操作系统中的 Python 子进程调用未按预期工作

python - 计算数组特定区域总和的最快方法

node.js - 管道流以在 node.js 中编辑 csv 文件

python - 索引错误 : list index out of range Python 2. 7.x

python - 值错误 : "undefined get method !" while evaluating u'action_ship_create()' in Odoo

python - 如何为字符串的最终出现创建正则表达式

python - 使用 Watson 对本地文件进行视觉识别

python - 从 CSV 文件中去除空格