在Python中给邮件附加文件时文件名为空?
下面这段代码运行得很好,唯一的问题就是发到邮件里的附件文件名是空的(在 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
你需要在消息的音频部分添加一个叫做 Content-Disposition header
的东西,这可以通过add_header
方法来实现:
file = open(file_name, 'rb')
audio = MIMEAudio(file.read())
file.close()
audio.add_header('Content-Disposition', 'attachment', filename=file_name)
msg.attach(audio)