在Python中将文件附加到电子邮件时,为什么会出现空白文件名?

10

以下代码片段运行良好,但是在电子邮件中生成的附件文件名称为空(在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()
1个回答

13

您需要使用add_header方法为消息中的audio部分添加Content-Disposition header

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

2
谢谢。这是我第三次适应Python电子邮件示例,它们真的需要重新编写。 - Sean W.
2
@Sean W. - 在这个例子中使用了add_header: http://docs.python.org/library/email-examples.html#id2 - David Webb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接