Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Email a Django FileField as an Attachment?

I need to send a models.FileField as an email attachment using Django. I've seen snippets that show how to do this with the raw request.FILES data (which still contains the Content-Type), but have not been able to find anything that shows how to do it once you've already saved the file in a models.FileField. The content type seems to be inaccessible from the models.FileField.

Can someone give me an example of how this would work? I'm beginning to think that I might have to store the Content-Type in the model when I save the file.

Thanks!

like image 733
Lyle Pratt Avatar asked Jun 28 '11 01:06

Lyle Pratt


2 Answers

I am using django-storages and so .path raises

NotImplementedError: This backend doesn't support absolute paths.

To avoid this, I simply open the file, read it, guess the mimetype and close it later, but having to use .attach instead of .attach_file magic.

from mimetypes import guess_type
from os.path import basename


f = model.filefield
f.open()
# msg.attach(filename, content, mimetype)
msg.attach(basename(f.name), f.read(), guess_type(f.name)[0])
f.close()
like image 189
shad0w_wa1k3r Avatar answered Oct 11 '22 17:10

shad0w_wa1k3r


Another approach:

from django.core.mail.message import EmailMessage

msg = EmailMessage(subject=my_subject, body=my_email_body, 
      from_email=settings.DEFAULT_FROM_EMAIL, to=[to_addressed])
msg.attach_file(self.my_filefield.path) # self.my_filefield.file for Django < 1.7
msg.send(fail_silently=not(settings.DEBUG))
like image 30
Tom Avatar answered Oct 11 '22 17:10

Tom