-1

When using Python 2.7 to automatically download Excel attachments from Outlook, I am receiving an error message: NameError: name 'att' is not defined. Strangely, the code was working fine until today.

I tried moving: att.SaveAsFile to inside loop.

# Imports arcpy library (Python for ArcGIS) and other libraries required
import arcpy
import os
import sys
import datetime
import win32com.client
from win32com.client import Dispatch
import csv
import pandas as pd
import numpy as np
from tempfile import NamedTemporaryFile
import logging
#import string

"""
Part I:  Downloads Excel Spreadsheet (Named Test) from Outlook
"""
# Reference: https://stackoverflow.com/questions/22399835/how-to-save-attachment-from-outlook-using-win32com-client-in-python
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
#messages= msg.Attachments
val_date = datetime.date.today()

sub_today = 'Test ' + date_string
att_today = 'Test ' + date_string+'.xlsx'

# Loop through messages and stop at message with today's subject and attachment.
for msg in all_inbox:
    if msg.Subject:
        new=msg.Subject
        if new.find('Test') !=-1 & new.find(date_string) !=-1:
            #print("Step 1")
            break

for att in msg.Attachments:
    if att.FileName:
        #print("Step 2")
        break

# Change Directory and Save Attachment  
os.chdir('My Directory')
att.SaveAsFile(os.getcwd()+'\\'+att_today)
logging.info('Finished Attachment Download')
jontheepi
  • 25
  • 4

1 Answers1

1

If list of attachments is empty, or none of att.FileName is set, then you get error above. There is a nice python trick to avoid it: you could use else for the for loop. Code in else would be executed if you iterated over collection and never hit break.

Here is example:

log = logging.getLogger(__name__)

for att in msg.Attachments:
    if att.FileName:
        break
else:
    log.error("file is not found")
    att = None

if att:
    att.SaveAsFile(att_today)
    log.info('Finished Attachment Download')

Is there only 1 attachment?

vav
  • 4,584
  • 2
  • 19
  • 39