1👍
I would just not supply a content type and let the recipient’s email client work it out. Unless it will be something unusual it shouldn’t be a problem.
RFC2616 states:
If and only if the media type is not
given by a Content-Type field, the
recipient MAY attempt to guess the
media type via inspection of its
content and/or the name extension(s)
of the URI used to identify the
resource.
but…
If you want to specify it then storing the content type on upload is a very good idea. It should be noted that django’s own docs say to verify the data from users
If you are on a *unix OS you could try to guess/inspect it:
import subprocess
subprocess.check_output(['file', '-b', '--mime', filename])
19👍
Attaching a models.FileField file to an email message is nice and simple in Django:
from django.core.mail import EmailMultiAlternatives
kwargs = 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()
- Best Practice for Context Processors vs. Template Tags?
- Django: sorl-thumbnail and easy-thumbnail in same project
- How show personalized error with get_object_or_404
- Django check if checkbox is selected
8👍
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()
- What does related_name do?
- How to connect Django in EC2 to a Postgres database in RDS?
- How to filter JSON Array in Django JSONField
- How can I use slugs in Django url
6👍
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))
- Defining a custom app_list in django admin index page
- Querying Many to many fields in django template
- DRF 3.6: How to document input parameters in APIView (for automatic doc generation)?