2011-04-11 75 views
10

下面的代碼片段工作正常,除了電子郵件中產生的附件文件名爲空白(該文件在gmail中以'noname'打開)之外。我究竟做錯了什麼?在python中將文件附加到電子郵件導致空白文件名?

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

回答

13

你需要使用一個add_header methodContent-Disposition header添加到消息的audio部分:

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電子郵件示例可行,他們確實需要重新編寫。 – 2011-04-11 14:47:48

+2

@Sean W. - 本例中使用'add_header':http://docs.python.org/library/email-examples.html#id2 – 2011-04-11 15:17:08

相關問題