[Django]-In Django, how do I save a file that has been uploaded in memory as an email attachment?

5👍

Looks like I was closer than I originally thought. The following did the trick.

import mimetypes
from django.core.mail import EmailMultiAlternatives

if request.method == 'POST':
    form = MyForm(request.POST, request.FILES)
    if form.is_valid():
        ...
        file = request.FILES['image']
        email = EmailMultiAlternatives(...)
        email.attach(file.name, file.file.getvalue(), mimetypes.guess_type(file.name)[0])
else:
    form = MyForm()

This makes use of the second method of file attachment in the Django docs, whereas I was originally attempting the first.

Leave a comment