使用python django下载电子邮件附件

时间:2016-03-01 06:10:45

标签: python django email-attachments

我正在尝试在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() 

2 个答案:

答案 0 :(得分:1)

您无法从django访问系统默认下载文件夹的名称。这取决于用户决定他/她的浏览器设置。您可以做的是告诉浏览器通过设置Content-Disposition将文件视为附件,然后它将打开正常的“另存为...”框,默认为下载文件夹。

实现这一目标的一些django代码如下所示:

response = HttpResponse()
response['Content-Disposition'] = 'attachment; filename="%s"' % fileName
return response

另见this question

答案 1 :(得分:0)

以下代码效果很好

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