Reputation: 63
I have a folder that I want to iterate through the emails and save the metadata per email to a csv file.
I want the csv output to look like:
emailSubject, sender, senderEmailAddress
<subject>, <sender>, <senderEmailAddress>
Here is my code so far:
import win32com.client
# Input
results = {}
f = open("testfile.txt", "w+")
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders.Item("Test Folder")
inbox = folder.Folders.Item("Inbox")
msg = inbox.Items
# Process
for x in msg:
senderEmail = x.SenderEmailAddress
sender = x.Sender
subject = x.Subject
I am new to python and am having troubles adding the section of code to add each element to a csv file. Any suggestions or ideas would be highly appreciated!
Upvotes: 0
Views: 391
Reputation:
Provided that the rest of your code works to your satisfaction, you can use the CSV module to write your desired file.
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders.Item("Test Folder")
inbox = folder.Folders.Item("Inbox")
msg = inbox.Items
f = open("testfile.txt", "w", newline="")
writer = csv.writer(f)
writer.writerow(["emailSubject", "sender", "senderEmailAddress"])
# Process
for x in msg:
senderEmail = x.SenderEmailAddress
sender = x.Sender
subject = x.Subject
writer.writerow([subject, sender, senderEmail])
f.close()
Upvotes: 1