Search code examples
pythonpathdirectorymime

Python: Mime message with Pictures


im trying to send png images using my mail and python. Here is a script i found :

# Import smtplib for the actual sending function
import smtplib

# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

COMMASPACE = ', '

# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = COMMASPACE.join(family)
msg.preamble = 'Our family reunion'

# Assume we know that the image files are all in PNG format
for file in pngfiles:
    # Open the files in binary mode.  Let the MIMEImage class automatically
    # guess the specific image type.
    with open(file, 'rb') as fp:
        img = MIMEImage(fp.read())
    msg.attach(img)

# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

source: https://docs.python.org/3/library/email-examples.html

My problem there is that when i want to precise the pngfiles path i write something like :

pngfiles="/Desktop/Test2"

only returning an error message such

Traceback (most recent call last):
  File "C:\Python27\work\Picture.py", line 46, in <module>
    fp = open(file, 'rb')
IOError: [Errno 13] Permission denied: '/'

Its really a silly problem but don't know how to write it properly... Any helps please ? :)

Thanks !


Solution

  • You file path:

    "/Desktop/Test2"
    

    and your python path:

    "C:\Python27\work\Picture.py"
    

    are conflicting (1st in Unix, 2nd is Windows).

    First thing would be to use a real windows path.

    pngfiles_folder = "C:\\Python27\\work\\"
    

    But you will also need a way to identify which files to attach (png in this case). To do so, you can use the glob package to create a list of files to attach:

    import glob
    for file in glob.glob("C:\\Python27\\work\\*.png"):
        ....