繁体   English   中英

使用Django发送带有可选附件的电子邮件

[英]Sending email with optional attachment in django

我正在处理一种发送带有可选附件的电子邮件的表单。

当我尝试发送电子邮件而不附加文件时。 我得到这个错误

在MultiValueDict中找不到键“文件”:{}

知道我在做什么错吗? 我想直接将其发送到电子邮件地址,而不将文件上传到我们的服务器

表格

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))

如果不发送文件,则request.FILE将是一个空白的类似于字典的对象。 文献资料

基于此,您需要检查此字典中是否存在密钥。 例子:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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