开发者

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

开发者 https://www.devze.com 2023-02-24 08:25 出处:网络
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?

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')
开发者_StackOverflow            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()


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号