0

一切正常,除非我在“消息”字段中通过“输入”添加新行。如果我不在消息文本字段中添加新行,它将通过。

我在这里想念什么?试图解决这个问题 2 天,在谷歌上没有类似的东西。

我觉得我的views.py配置可能有问题:

def success(request):
    return render(request, 'home/success.html')

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # send email code goes here
            sender_name = form.cleaned_data['name']
            sender_email = form.cleaned_data['email']
            sender_phone = form.cleaned_data['phone']
            sender_message = form.cleaned_data['message']
            subject = "Enquiry: {0}".format(sender_message[:50])
            message = "New message from {0}\n phone number: {1}\n email: {2}\n\n{3}".format(sender_name, sender_phone, sender_email, sender_message)
            recipients = ['john.smith@gmail.com']
            sender = "{0}<{1}>".format(sender_name, sender_email)
            try:
                send_mail(subject, message, sender, recipients, fail_silently=False)
            except BadHeaderError:
                return HttpResponse('Invalid header found')
            return HttpResponseRedirect('success')
    else:
        form = ContactForm()

    return render(request, 'home/contact.html', {'form': form})

有任何想法吗?

4

1 回答 1

1

文档中所述,BadHeaderError提出 a 以“通过禁止标头值中的换行符来防止标头注入”。

由于您将部分内容sender_message直接复制到subject标题中,因此您也可能包含换行符。简单的解决方案是先将它们剥离。

sender_message = form.cleaned_data['message']
clean_message = sender_message.replace('\n', '').replace('\r', '')
subject = "Enquiry: {0}".format(clean_message[:50])
于 2020-04-23T08:37:47.940 回答