Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Why am I receiving this NameError: when attempting to add an outlooks email Attachment's FileName to a list?

I have a script that iterates over a folder in my outlook account, and then writes each emails metadata to a csv file. I am stuck on getting the attachments filename in the data. I keep receiving a NameError.

Here is my code:

import win32com.client
import datetime as date

# Input
f = open("testfile.txt", "w+")


outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders.Item("TestFolder")
inbox = folder.Folders.Item("Inbox")
msg = inbox.Items

# Process
list = []

for x in msg:
    senderEmail = x.SenderEmailAddress
    sender = x.SenderName
    subject = x.Subject
    if x.Attachments:
        for f in x.Attachments:
            attachment = f.FileName
    sum = [subject, sender, senderEmail, attachment]
    list.extend(sum)

Here is the error I keep receiving:

enter image description here

Any idea as to why I keep receiving this error?

question from:https://stackoverflow.com/questions/65945389/why-am-i-receiving-this-nameerror-when-attempting-to-add-an-outlooks-email-atta

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

1 Answer

0 votes
by (71.8m points)

If x.Attachments doesn't exists then it doesn't create attachment but you try to use it.

If you want to create sum only when there is attachment then you should change indentations

if x.Attachments:
     for f in x.Attachments:
         attachment = f.FileName
         sum = [subject, sender, senderEmail, attachment]
         #list.extend(sum)
         list.append(sum)

If you want to create also when there is no attachment then you need else

Eventually you can use None for attachment and it will be easier to work with list which have the same number of items.

if x.Attachments:
     for f in x.Attachments:
         attachment = f.FileName
         sum = [subject, sender, senderEmail, attachment]
         #list.extend(sum)
         list.append(sum)
 else:
     sum = [subject, sender, senderEmail, None]
     #list.extend(sum)
     list.append(sum)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...