Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

python - How to iterate emails in a outlook folder and put it in a csv file per email?

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!

question from:https://stackoverflow.com/questions/65944156/how-to-iterate-emails-in-a-outlook-folder-and-put-it-in-a-csv-file-per-email

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...