Search code examples
pythonemailpython-2.7mime

Python send email with an attachment


I'm testing out Python, learning how to use it.

Recently I've been testing out different ways to send e-mails using SMTP, without and with attachments.

So far, after reading the Python documentation and other topics here on Stackoverflow I got what I needed and now can send emails with attachments, yay me!

I stumbled across this page, http://www.tutorialspoint.com/python/python_sending_email.htm, which offered what it looks like to me, another way to attach files.

I used this before in a script where I had 4 files to attach (lets hope I insert the code correctly):

   for f in attach:
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(open(f, 'rb').read())
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(f))
    msg.attach(part)

But the tutorial posted above uses a different way and I tried it out because why not, just copy and paste and enter my email, SMTP just to see it in action, and try changes after. However, the last bit of code:

message = part1 + part2 + part3

.. does not work. My SMTP refuses saying [ERNO10053]. Just sending one part works fine.

Could someone who is more familiar in Python explain to me what it means to use boundaries? I can see that it is "--" followed by a unique marker. But I don't understand really why you need them, and whats going on in this script really.

I'm a newb.

Cheers!


Solution

  • This boundaries is part of MIME specification. They are used as separator between attachments.

    Error 10053 means connection abort.