Unable to save email attachment from outlook to local drive
Question:
i have written the below code to save email attachment from outlook with specific subject but its throwing an error.
Below is the code :
import win32com.client
import os
outlook = win32com.client.Dispatch('outlook.application').GetNamespace("MAPI")
inbox = outlook.Folders('xyz.com').Folders("Inbox")
messages = inbox.Items
for msg in messages:
if 'Subject' in msg.Subject:
print(msg.Subject)
if not os.path.exists('C:xyzreports'):
for atch in msg.Attachments:
atch.SaveAsFile(os.getcwd() + 'C:xyzreports' + atch.Filename)
Error msg **: (-2147352567, ‘Exception occured.’,(4096, ‘Microsoft Outlook’, ‘Cannot save the attachment. File name or directory name is not valid.’ None, 0, -2147024773), None)
Answers:
Change the line
atch.SaveAsFile(os.getcwd() + 'H:AtulSave' + atch.Filename)
to
atch.SaveAsFile('H:AtulSave' + atch.Filename)
i have written the below code to save email attachment from outlook with specific subject but its throwing an error.
Below is the code :
import win32com.client
import os
outlook = win32com.client.Dispatch('outlook.application').GetNamespace("MAPI")
inbox = outlook.Folders('xyz.com').Folders("Inbox")
messages = inbox.Items
for msg in messages:
if 'Subject' in msg.Subject:
print(msg.Subject)
if not os.path.exists('C:xyzreports'):
for atch in msg.Attachments:
atch.SaveAsFile(os.getcwd() + 'C:xyzreports' + atch.Filename)
Error msg **: (-2147352567, ‘Exception occured.’,(4096, ‘Microsoft Outlook’, ‘Cannot save the attachment. File name or directory name is not valid.’ None, 0, -2147024773), None)
Change the line
atch.SaveAsFile(os.getcwd() + 'H:AtulSave' + atch.Filename)
to
atch.SaveAsFile('H:AtulSave' + atch.Filename)