简体   繁体   中英

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:

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. 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:

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. You ended up writing one row where each column is a full line from the csv you wanted. Instead, just write the body as it is.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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