Python is just beautiful! In my last post I mentioned how you can setup an email server. Now, here’s the code I use to send a bunch of images as attachments with my outgoing emails. This code snippet was taken from the Python manual. But unfortunately the code was not complete. So, I had to hack through it and configure it to suit my needs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#!/usr/bin/python import smtplib,glob,os from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart COMMASPACE = ', ' msg = MIMEMultipart() msg['Subject'] = 'Our family reunion' me = "masnun@leevio.com" family = ['masnun@gmail.com','jotil21@gmail.com'] msg['From'] = me msg['To'] = COMMASPACE.join(family) msg.preamble = 'Our family reunion' path = "images/" pngfiles = glob.glob( os.path.join(path, "*.png") ) for file in pngfiles: # Open the files in binary mode. Let the MIMEImage class automatically # guess the specific image type. fp = open(file, 'rb') img = MIMEImage(fp.read()) fp.close() msg.attach(img) # Send the email via our own SMTP server. s = smtplib.SMTP("localhost") s.sendmail(me, family, msg.as_string()) s.quit() |
It currently reads the “images” directory and mails out the png files. But if you look at the codes, you’ll see that the codes can be easily changed to send other files as well 🙂
I love Python!
PS: I am looking for a good way to attach files using PHP. The way I found was messy! I know the huge PHP community certainly has something better to offer. I will post it as soon as I find it 🙂