[英]Downloading email attachments using python django
我正在嘗試在python中開發郵件客戶端
我能夠解析帶有附件的電子郵件正文,並顯示在django模板中。
現在,當我單擊附件名稱時,需要下載附件。
我所能找到的就是使用python將文件下載到特定文件夾的方法。 但是,當我單擊瀏覽器上的文件名時,如何將其下載到系統的默認下載文件夾中
下面是我嘗試的代碼示例
def download_attachment(request):
if request.method == 'POST':
filename=request.POST.get('filename','')
mid=request.POST.get('mid','')
mailserver = IMAP_connect("mail.example.com",username, password)
if mailserver:
mailserver.select('INBOX')
result, data = mailserver.uid('fetch', mid, "(RFC822)")
if result == 'OK':
mail = email.message_from_string(data[0][1])
for part in mail.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
fileName = part.get_filename()
if filename != fileName:
continue
detach_dir = '.'
if 'attachments' not in os.listdir(detach_dir):
os.mkdir('attachments')
if bool(fileName):
filePath = os.path.join(detach_dir, 'attachments', fileName)
if not os.path.isfile(filePath) :
print fileName
fp = open(filePath, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
return HttpResponse()
您無法從django訪問系統默認下載文件夾的名稱。 這取決於用戶來決定他/她的瀏覽器設置。 您可以做的是通過設置Content-Disposition
告訴瀏覽器將該文件視為附件,然后它將打開通常的“另存為...”框,該框默認為下載文件夾。
一些使這種情況發生的django代碼如下所示:
response = HttpResponse()
response['Content-Disposition'] = 'attachment; filename="%s"' % fileName
return response
另請參閱此問題 。
下面的代碼工作得很好
def download_attachment(request):
if request.method == 'GET':
filename=request.GET.get('filename','')
mid=request.GET.get('mid','')
mailserver = IMAP_connect("mail.example.com",username, password)
if mailserver:
mailserver.select('INBOX')
result, data = mailserver.uid('fetch', mid, "(RFC822)")
if result == 'OK':
mail = email.message_from_string(data[0][1])
for part in mail.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
fileName = part.get_filename()
if filename != fileName:
continue
if bool(fileName):
response = HttpResponse(part.get_payload(decode=True))
response['Content-Disposition'] = 'attachment; filename="%s"' % fileName
return response
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.