Reputation: 301
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:
Upvotes: 1
Views: 1126
Reputation: 77337
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])
Upvotes: 2