0

Everything works except when I add a new line via 'enter' in the "Message" field. It goes through if I don't add new lines in the message textfield.

What am i missing here? Tried to solve this problem for 2 days, nothing similar on google.

I feel like there could be the problem of my views.py config:

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

Any ideas?

reivan
  • 29
  • 1
  • 8
  • 1
    Seems like there must be a newline in `sender_message`. As described in the documentation, you can't have newlines in a header, and you use the first 50 characters of `sender_message` in the subject header. Try stripping out newlines first. – Kevin Christopher Henry Apr 21 '20 at 00:34
  • OMG what a foolish mistake! Thank you for pointing it out, it works now! I edited the subject line in the following way: `subject = "Enquiry {0}".format(sender_message[:50].replace('\n', '').replace('\t','').replace('\r',''))` – reivan Apr 21 '20 at 13:11
  • 1
    Happy to help. I added an answer in case this helps someone else in the future. – Kevin Christopher Henry Apr 23 '20 at 08:38

1 Answers1

1

As described in the documentation, a BadHeaderError is raised to "protect against header injection by forbidding newlines in header values".

Since you're copying part of sender_message directly into the subject header, you may be including newlines as well. The simple solution is to strip them out first.

sender_message = form.cleaned_data['message']
clean_message = sender_message.replace('\n', '').replace('\r', '')
subject = "Enquiry: {0}".format(clean_message[:50])
Kevin Christopher Henry
  • 46,175
  • 7
  • 116
  • 102