1

So, I'm relatively new to python and I'm trying to send email with attachments. I'm using the guide described on StackOverflow here: How to send email attachments with Python

I'm using the following code to attach files...

for f in glob.glob('./*/*'):
    path = f.split('/')

    with open(f, "rb") as fil:
        msg.attach(MIMEApplication(
            fil.read(),
            Content_Disposition = 'attachment; filename="' + path[-1] + '"'
        ))
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(emailFrom, emailTo, msg.as_string())
server.quit()

When I receive the email, the attachments are all called "noname". If I open the original email in Gmail, it shows the attachments as follows:

Content-Type: application/octet-stream; Content-Disposition="attachment;
    filename=\"Daily Report.txt\""

Why is the name not coming through properly?

Community
  • 1
  • 1
John Chrysostom
  • 3,973
  • 1
  • 34
  • 50

1 Answers1

3

For reasons completely lost on me, the following code works. Seems like it's doing the same thing, though. Anybody know what's going on?

for f in glob.glob('./*/*'):
    path = f.split('/')

    with open(f, 'rb') as fil:
        submsg = MIMEApplication(fil.read())
        submsg.add_header('Content-Disposition', 'attachment', filename = path[-1])

        msg.attach(submsg)
John Chrysostom
  • 3,973
  • 1
  • 34
  • 50
  • 1
    From [the docs](https://docs.python.org/2/library/email.mime.html#email.mime.base.MIMEBase), "The MIMEBase class always adds a Content-Type header (based on _maintype_, _subtype_, and _params_),` Why they designed the API this way is beyond me, but all keyword parameters to any MIME constructor are added to Content-Type. – Robᵩ May 05 '15 at 19:04