Python Outlook vexing file attachment error

741 views Asked by At

So, with this code simply trying to test sending an email attachment using outlook with python:

Error:

Traceback (most recent call last):
  File "c:\python_code.py", line 10, in <module>
    mail.Attachments.Add("<path to file on C:Drive>")
  File "<COMObject <unknown>>", line 2, in Add
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'File name or directory name is not valid.', None, 0, -2147024773), None)

I have tried nearly ten stackoverflow and other solutions which didn't precisely meet this error, but were close. Tried this with different files, filetypes, same error. All the files are accessible and otherwise normal. Pretty much at the end of options at this point. Ideas?

Below is the code I am using:

file = "<full path to my file to be attached>"

import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = '<my email address>'
mail.Subject = 'Example File Attached'
mail.Body = 'Please see the attached file as the Example'
mail.Attachments.Add(file)
mail.Send()
1

There are 1 answers

1
John Taylor On

It turns out, putting an 'r' before the filepath, solved the problem it appears. Tried that a few times before posting and it didn't work, now, for no know reason, it works.