I am trying to develop a mail client in python
I am able to parse the email body with attachment and display in my django template.
Now I need to download the attachment when I click on the attachment name.
All I could find is the way to download file to a specific folder using python. But How could I download it to the default downloads folder of system when I click on the filename on my browser
Below is the code sample I 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])
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()