Forums

Sending email Server Error 500

I have a "contact" page on my site. After the user fills it out and hits submit, it sends an email to me.
Works locally but not on PA. Here's the traceback:

Traceback (most recent call last):
  File "/home/rightswerve/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/rightswerve/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/rightswerve/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/rightswerve/indie_site/main/contact/views.py", line 17, in emailView
    send_mail(subject, message, from_email, ['indietown@gmail.com'])
  File "/home/rightswerve/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/mail/__init__.py", line 60, in send_mail
    return mail.send()
  File "/home/rightswerve/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/mail/message.py", line 291, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "/home/rightswerve/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 110, in send_messages
    sent = self._send(message)
  File "/home/rightswerve/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 126, in _send
    self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n'))
  File "/usr/lib/python3.7/smtplib.py", line 867, in sendmail
    raise SMTPSenderRefused(code, resp, from_addr)
smtplib.SMTPSenderRefused: (530, b'5.5.1 Authentication Required. Learn more at\n5.5.1  https://support.google.com/mail/?p=WantAuthError k7sm7580313qkf.40 - gsmtp', 'tester@gmail.com')

In the django app, I have set up my settings like:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = os.getenv("RECIPIENT_NAME")
EMAIL_HOST_PASSWORD = os.getenv("RECIPIENT_PASS")
EMAIL_PORT = 587

And I have set the env values in a .env, followed this: http://help.pythonanywhere.com/pages/environment-variables-for-web-apps
and it does appear to register.

views.py:

def emailView(request):
    if request.method == 'GET':
        form = ContactForm()
    else:
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            from_email = form.cleaned_data['from_email']
            message = form.cleaned_data['message'] + "\nFROM\n" + str(from_email)
            try:
                send_mail(subject, message, from_email, ['indietown@gmail.com'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('contact:success')
    return render(request, "contact/contact.html", {'form': form})


def successView(request):
    return HttpResponse('Thanks! I\'ll get back to you shortly.')

Still, 500 error. What might be going on?

Is the email address at the end of the smtplib.SMTPSenderRefused the one that you expect? If so, I think we can be reasonably sure that at least the correct EMAIL_HOST_USER is being picked up from your .env file, which would imply that the EMAIL_HOST_PASSWORD is too.

If that is the case, perhaps you could try setting up an app-specific password -- Google have very strict security checks for incoming connections from cloud computing services (as a perfectly reasonable spam-reduction measure) and we've found that app-specific passwords work better. This page is a good starting point on how to set one up.

I've made a 16 digit app password and replaced the .env with that pw. Still receiving a 500 server error. What should I try next? @giles
Just to confirm -- a contact form such as this through google must have been done by someone on pythonanywhere, correct? It's possible?

It looks like there's a long discussion of the various things you can try here

Just reporting back..
Nothing I've tried works! haha.

here's what I've tried: installing and using app-specific password.
changing normal password to a stronger 16 digit pass. all of that done with less-secured apps setting turned to "ON". visiting https://accounts.google.com/DisplayUnlockCaptcha and clicking to allow access, then retrying all of the above.
the only thing I havent tried is creating a new gmail account and using that.

know of any other options for achieving the kind of contact form I'm implementing? Is sendgrid a good use case for this? My understanding is that it's mainly for mass email send for marketing purposes.

We have no visibility into Google's authentication process, so there is limited help that we can give on that front.

Any service that accepts email on SMTP and sends it out for you should be fine to use in a form like that.