10

The following snipit of code works fine, except for the fact that the resulting attachment file name is blank in the email (the file opens as 'noname' in gmail). What am I doing wrong?

file_name = RecordingUrl.split("/")[-1]
            file_name=file_name+ ".wav"
            urlretrieve(RecordingUrl, file_name)

            # Create the container (outer) email message.
            msg = MIMEMultipart()
            msg['Subject'] = 'New feedback from %s (%a:%a)' % (
From, int(RecordingDuration) / 60, int(RecordingDuration) % 60)

            msg['From'] = "noreply@example.info"
            msg['To'] = 'user@gmail.com'
            msg.preamble = msg['Subject']                
            file = open(file_name, 'rb')
            audio = MIMEAudio(file.read())
            file.close()
            msg.attach(audio)

            # Send the email via our own SMTP server.
            s = smtplib.SMTP()
            s.connect()
            s.sendmail(msg['From'], msg['To'], msg.as_string())
            s.quit()
Sean W.
  • 4,944
  • 8
  • 40
  • 66

1 Answers1

13

You need to add a Content-Disposition header to the audio part of the message using the add_header method:

file = open(file_name, 'rb')
audio = MIMEAudio(file.read())
file.close()
audio.add_header('Content-Disposition', 'attachment', filename=file_name)
msg.attach(audio)
David Webb
  • 190,537
  • 57
  • 313
  • 299
  • 2
    Thank you. This is the third adaptation I've had to do to make python email examples workable, they really need to be re-written. – Sean W. Apr 11 '11 at 14:47
  • 2
    @Sean W. - `add_header` is used in this example: http://docs.python.org/library/email-examples.html#id2 – David Webb Apr 11 '11 at 15:17