Search code examples
djangofile-uploademail-attachments

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


I am building an email gateway for our clients and need to be able to attach the files they upload to the email. I am using EmailMultiAlternatives to send the email and a FileField for the upload. The problem happens when I try to connect the two. I have the following logic in my view.

if request.method == 'POST':
    form = MyForm(request.POST, request.FILES)
    if form.is_valid():
        ...
        email = EmailMultiAlternatives(...)
        email.attach(request.FILES['image'])
else:
    form = MyForm()

This results in "No exception message supplied" and the following values in debug:

content: None
filename: <InMemoryUploadedFile: ImageFile.png (image/png)>
mimetype: None

So it looks like for some reason, there is no file content. Not sure what's going on here. Examples in the docs save the file to a model, but there is no model to save the file to here. Ideally, I would just like to pass the file content directly to the attach method and send it on. Any ideas on how to make this work?


Solution

  • 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.