5

I am trying to send and email in Django forms with attached file, but i cant figure out how to send the file(uploaded by user) without saving it locally. I have my form:

class PrintForm(forms.Form):
    contact_name = forms.CharField(required=True)
    contact_email = forms.EmailField(required=True)
    supervisor = forms.ChoiceField(
        choices=[(str(sup.email), str(sup.name)) for sup in Supervisors.objects.all()]
    )
    file = forms.FileField()
    content = forms.CharField(
        required=True,
        widget=forms.Textarea
    )

and my view:

def print(request):
   #  context = dict()
   #  context['printers'] = Printer.objects.all()
   #   return render(request, 'threeD/print.html', context)

   if request.method == 'POST':
        form = PrintForm(data=request.POST, request = request)

        if form.is_valid():
            contact_name = request.POST.get('contact_name', '')
            contact_email = request.POST.get('contact_email', '')
            form_content = request.POST.get('content', '')
            supervisor = form.cleaned_data['supervisor']
            template = get_template('threeD/email/contact_template_for_printing.txt')
            context = Context({
                'contact_name': contact_name,
                'supervisor': supervisor,
                'contact_email': contact_email,
                'form_content': form_content,
            })
            content = template.render(context)
            subject = "New message"

            try:
                email = EmailMessage(
                    subject,
                    content,
                    contact_email,
                    [supervisor],
                    headers={'Reply-To': contact_email}
                )
                #email.attach(...)
                email.send()
            except:
                return "Attachment error"

            messages.success(request, "Thank you for your message.")
            return redirect('/index/print/')

   else:
            form = PrintForm(request=request)
   context_dict = {}
   context_dict['printers'] = Printer.objects.all()
   context_dict['form'] = form
   return render(request, 'threeD/print.html', context_dict)

So in my view, when i am sending an email, is there a way to call email.attach(file) which would attach file to a mail and send it but without locally saving the file? (form and view works fine, without file feature implementation)

EDIT:
here is HTML code snippet, where i call for the form:

 <div class="panel-body">
        <form role="form" action="" method="post">
            {% csrf_token %}
            {% load bootstrap %}
               {{ form|bootstrap }}

            <div class="text-center">
                <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-send"></span>    Send a message</button>
            </div>
        </form>
 </div>

Any help would be very much appreciated. Thanks!

1 Answer 1

12

Something like this:

def send_email(request):
    ...
    email = EmailMessage(
        subject,
        content,
        contact_email,
        [to],
        headers={'Reply-To': contact_email}
    )
    if request.FILES:
        uploaded_file = request.FILES['file'] # file is the name value which you have provided in form for file field
        email.attach(uploaded_file.name, uploaded_file.read(), uploaded_file.content_type)
    email.send()
12
  • Thank you very much for your help. Is there anything wrong in my forms when i say "file = forms.FileField()" ? Because using your approach for views, it still doesnt work, and it writes "This field is required." near the field after submitting, like there would be no file attached, even if it is
    – Ilja Leiko
    Apr 17, 2017 at 15:17
  • Edit your question to add html code of the form and also request.FILES value when the control comes to the view.
    – Abijith Mg
    Apr 17, 2017 at 15:21
  • I have added my html code, which is quite primitive. I am sorry to say, but i'm afraid i dont know how to get request.FILES value when the control comes to the view. :/
    – Ilja Leiko
    Apr 17, 2017 at 15:31
  • There are 2 ways, use python breakpoint: import pdb; pdb.set_trace() at the start of the view (server control will stop there) or add 'print request.FILES' this will print the value in server log.
    – Abijith Mg
    Apr 17, 2017 at 15:55
  • Hmmm. that's weird. I have first tried python breakpoint and after from submission i got a Pdb in console. I typed in request.FILE and it says: "*** AttributeError: 'WSGIRequest' object has no attribute 'FILE'". and i have tried print(request.FILE), and i get error "'MultiValueDict' object has no attribute 'method'" and Exception Value: 'WSGIRequest' object has no attribute 'FILE'
    – Ilja Leiko
    Apr 17, 2017 at 16:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.