tamus tamus - 24 days ago 13
Python Question

How to use wildcards in filename to attach file to email using python

I want to send email with attached jpg file when it is created and then delete the file, leaving no jpg files in the folder. The actual name of the file will change with date and time but I won't know what it is. I tried using this

#Email body
rstime = datetime.datetime.now().strftime('%d %b %Y at %H:%M:%S')
body = 'Picture saved of movement at front of house ' + str(rstime)

msg.attach(MIMEText(body, 'plain'))
fp = open('/mnt/usb/motion/*.jpg', 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)

#remove file after emailing
os.remove('/mnt/usb/motion/*.jpg')


this gives me an error -
IOError: [Errno 2] No such file or directory: '/mnt/usb/motion/*.jpg'

What is wrong with my code? If I enter the filename it works but I want to use with wildcard.

Answer

You cannot use the wildcard in this manner. What should happen, if two files would match the wildcard? Should both files be opened in the same object?

You can use the wildcard with e.g. the python glob module:

import glob
# Email body
rstime = datetime.datetime.now().strftime('%d %b %Y at %H:%M:%S')
body = 'Picture saved of movement at front of house ' + str(rstime)

msg.attach(MIMEText(body, 'plain'))
files = glob.glob("/mnt/usb/motion/*.jpg")
firstFile = files[0]
fp = open(firstFile, "rb");
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)

# remove file after emailing
os.remove(firstFile)
Comments