Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending email with attached file in Django

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!

like image 248
Ilja Leiko Avatar asked Apr 17 '17 14:04

Ilja Leiko


1 Answers

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()
like image 88
Abijith Mg Avatar answered Nov 03 '22 21:11

Abijith Mg