12

Im trying to read email and download the attachment to my own folder using win32com module in Python, I stopped at getting the attachment object:

from win32com.client import Dispatch
import datetime as date

outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
val_date = date.date.today()

sub_today = 'Hi'
att_today = 'Attachment.xlsx'
for msg in all_inbox:
    if msg.Subject == sub_today:
        break

for att in msg.Attachments:
    if att.FileName == att_today:
        break

att.SaveAsFile('new.xlsx')
att.ExtractFile('new.xlsx')
open(att)    
att.WriteToFile('x')

None of the last 4 lines work...

>>> att.ExtractFile('new.xlsx')
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: <unknown>.ExtractFile

>>> open(att) 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, instance found

>>> att.WriteToFile('x')
 raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: <unknown>.WriteToFile

att.SaveAsFile('new.xlsx') has no error, but there is no such file in the working directory. Seems that the line was just ignored...

Could anyone help? Thanks in advance!

2
  • 1
    You can probably accept your answer by now :). Commented Mar 27, 2014 at 20:18
  • Are you able to post your full resolved code on here? I'm trying to do the same with your code and am running into the same issue. Commented May 14, 2019 at 14:59

3 Answers 3

13

Just to update, I have solved this issue by claiming both dir and the file name itself in SaveAsFile:

att.SaveAsFile(os.getcwd() + '\\new.xlsx')

It is not like most threads I've seen here saying that you only need to put path in it. Actually both path and file name are needed.

Also, weirdly, you have to put os.getcwd() here since Python wouldn't recognize current running dir - in R, after we set working dir with getwd(), we are able to write to any file at this location.

Sign up to request clarification or add additional context in comments.

1 Comment

It is very common usage of the term "full path" to imply "full path specification including the filename". The threads you've seen might've been correct. :-)
4

Where do you think the current working directory is? I'd say you are looking at the wrong folder, SaveAsFile in general works just fine.

Simply pass a full path to SaveAsFile, that should solve your problem.

1 Comment

Thanks I finally solved it by announcing both dir and the file name:att.SaveAsFile(os.getcwd() + '\\new.xlsx')
0

if you want to just save the attachment, comment out the last 3 lines and write the entire directory in last 4th line to save at a specific location.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.