Search code examples
pythonoutlookglobpywin32

Python/Outlook Attachment: "cannot find this file..verify exists"


I wrote the following to use Outlook to send an email, but it is not able to locate the file I want to reference:

import win32com.client as win32
import glob
import os
import datetime

outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = '[email protected]'
mail.Subject = 'Message subject'
mail.Body = 'Message body'
mail.HTMLBody = '<h2>HTML Message body</h2>'# this field is optional

#In case you want to attach a file to the email

newestfile  = max(glob.iglob('*.csv'), key=os.path.getctime))
mail.Attachments.Add(newestfile)

mail.Send()

if i try to print(max(glob.iglob('*.csv'), key=os.path.getctime))) it returns the right path. Directly writing the path in newestfile also works fine. How come it doesn't attach in its current form?

I also tried converting the path to a string, that did not work


Solution

  • From the Attachments.Add Method (Outlook) docs, the first argument is:

    The source of the attachment. This can be a file (represented by the full file system path with a file name) or an Outlook item that constitutes the attachment.