How to Email a Django FileField as an Attachment? How to Email a Django FileField as an Attachment? django django

How to Email a Django FileField as an Attachment?


Attaching a models.FileField file to an email message is nice and simple in Django:

from django.core.mail import EmailMultiAlternativeskwargs = dict(    to=to,    from_email=from_addr,    subject=subject,    body=text_content,    alternatives=((html_content, 'text/html'),))message = EmailMultiAlternatives(**kwargs)message.attach_file(model_instance.filefield.path)message.send()


Another approach:

from django.core.mail.message import EmailMessagemsg = 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.7msg.send(fail_silently=not(settings.DEBUG))


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_typefrom os.path import basenamef = model.filefieldf.open()# msg.attach(filename, content, mimetype)msg.attach(basename(f.name), f.read(), guess_type(f.name)[0])f.close()