将文件附加到python中的电子邮件会导致空白文件名?

Sea*_* W. 10 python email filenames attachment

下面的代码片段工作正常,除了电子邮件中生成的附件文件名是空白的(该文件在gmail中打开为'noname').我究竟做错了什么?

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()
Run Code Online (Sandbox Code Playgroud)

Dav*_*ebb 13

您需要使用以下方法向邮件的一部分添加Content-Disposition标头:audioadd_header

file = open(file_name, 'rb')
audio = MIMEAudio(file.read())
file.close()
audio.add_header('Content-Disposition', 'attachment', filename=file_name)
msg.attach(audio)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.这是我为使python电子邮件示例可行而必须做的第三次调整,它们确实需要重新编写. (2认同)
  • @Sean W. - 在这个例子中使用`add_header`:http://docs.python.org/library/email-examples.html#id2 (2认同)