Downloading email attachments using python django -
i trying develop mail client in python
i able parse email body attachment , display in django template.
now need download attachment when click on attachment name.
all find way download file specific folder using python. how download default downloads folder of system when click on filename on browser
below code sample tried
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]) part in mail.walk(): if part.get_content_maintype() == 'multipart': continue if part.get('content-disposition') 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()
you can't access name of system's default downloads folder django. that's user decide in his/her browser settings. can tell browser treat file attachment setting content-disposition
, , open normal "save as..." box default downloads folder.
some django code makes happen like:
response = httpresponse() response['content-disposition'] = 'attachment; filename="%s"' % filename return response
see this question.
Comments
Post a Comment