Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching file to an email in python leads to a blank file name?

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'] = "[email protected]"
            msg['To'] = '[email protected]'
            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()
like image 262
Sean W. Avatar asked Apr 11 '11 14:04

Sean W.


1 Answers

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)
like image 117
Dave Webb Avatar answered Nov 03 '22 10:11

Dave Webb