Python: Sending a bunch of images as email attachments

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.

#!/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 :)

This entry was posted in Blog Post and tagged , . Bookmark the permalink.

One Response to Python: Sending a bunch of images as email attachments

  1. Pingback: Python: Sending a bunch of images as email attachments « maSnun.com MoinMoin Wiki

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">