简体   繁体   中英

Sending email with optional attachment in django

I am working on a form to send email where have optional attachment.

When I try to send the email without attach a file. I got this error

Key 'file' not found in MultiValueDict: {}

Any idea what I am doing wrong? I would like to send it directly to the email address without upload the file to our server

forms.py

class jopcion(forms.Form):
    subject = forms.CharField(max_length=100)
    thecontent = forms.CharField(widget=forms.Textarea)
    file = forms.FileField(widget= forms.FileInput (attrs={'name': 'file'}),required=False)

views.py

def novo(request, template_name='mailme.html'):
    if request.method == "POST":
            formulario = jopcion(request.POST or None, request.FILES or None)
            if formulario.is_valid():
                        subject = request.POST['subject']
                        message = request.POST['thecontent']
                        attach = request.FILES['file']

                        destination = 'testing@gmail.com'
                        html_content = (subject,message,attach)
                        msg = EmailMultiAlternatives('Customer email address', html_content, 'from@server.com', [destination])
                        msg.attach(attach.name, attach.read(), attach.content_type)
                        msg.attach_alternative(html_content, 'text/html')#definimos el contenido como html
                        msg.send() #enviar en correo
                        return render_to_response('done.html', context_instance=RequestContext(request))
        else:
                    formulario = jopcion()

        ctx = {'form': formulario, 'text_dc': file}
        return render_to_response(template_name, ctx , context_instance = RequestContext(request))

If you don't send a file, request.FILE will be a blank dictionary-like object. Documentation

Based on this, you need to check if key is present at this dict. examples:

 if 'file' in request.FILES:
     attach = request.FILES['file']

 #or
 attach = request.FILES.get('file')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM