简体   繁体   English

如何读取 CSV Email 正文并将其保存到 CSV 文件中?

[英]How can I read in a CSV Email Body and save it to a CSV file?

I receive automated emails from Outlook with a body in a CSV format like this:我收到来自 Outlook 的自动电子邮件,其正文采用 CSV 格式,如下所示:

serverName,package,packageVersion
testMachine,Docker,1.0
testMachine,K8s,2.0

My goal is to read the contents of the body with Python, and output it to a CSV file.我的目标是用 Python 和 output 将正文的内容读取到 CSV 文件中。 Below currently reads the contents but writes the contents to the same row in the CSV file instead of writing it to the row beneath it:下面当前读取内容,但将内容写入 CSV 文件的同一行,而不是将其写入其下方的行:

import win32com.client
import os
from datetime import datetime, timedelta
import csv


def retreiveEmail():
    outlook = win32com.client.Dispatch(
        "outlook.application"
    )  # Iniates Session with Outlook
    mapi = outlook.GetNamespace("MAPI")  # Establishes namespace being worked in

    inbox = mapi.GetDefaultFolder(6)  # Sets the folder to 'Inbox'

    deployMessages = inbox.Items.Restrict(
        "[SenderEmailAddress] = '<EmailAddress>'"
    )  # This ensures we're only interested in the emails coming from a specific email

    messageList = (
        []
    )  # This is a current work around to get the most recent email

    for message in deployMessages:
        messageList.append(message.body)

    # print(messageList[1])

    # messageList[-1].split()

    with open("test.csv", "w") as new_file:

        csv_writer = csv.writer(new_file, delimiter=",")
        csv_writer.writerow(messageList[-1].splitlines())


retreiveEmail()

Screenshot:截屏:

输出

The body is already a CSV so there is no need to use csv.writer to write it. body 已经是 CSV 所以没有必要使用 csv.writer 来写它。 You ended up writing one row where each column is a full line from the csv you wanted.您最终写了一行,其中每一列都是您想要的 csv 的整行。 Instead, just write the body as it is.相反,只需按原样编写正文。

with open("test.csv", "w") as new_file:
    new_file.write(messageList[-1])

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

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