I have a Django app deployed on Heroku. In one of the sections I'm sending email to the user using SMTP Gmail settings. The emails are sent successfully when I run project locally but not on my deployed project on Heroku.
I've seen many of the other answers on Stackoverflow but none of them resolves my issue. I've enabled the 2FA on my Google account and generated an APP password and using that password in my settings file. Turning on allow_less_secure_app option isn't suggested by other developers
My settings.py
file email settings-
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ.get('EMAIL_USER2')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS2')
My views.py
view handling the mail-
def index(request)
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
message = form.cleaned_data['message']
email = form.cleaned_data['email']
subject = "You got a message"
thoughts = "{} by {}".format(message,email)
recipients = ['[email protected]']
sender = '[email protected]'
send_mail(subject, thoughts, sender ,recipients,fail_silently=False)
return HttpResponse()
else:
form = MyForm()
return render(request,'my_webapp/index.html',{'form':form})
The error I'm getting in Heroku logs is-
raise SMTPAuthenticationError(code, resp)
2019-10-07T18:22:12.174365+00:00 app[web.1]: smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials w2sm9789664qtc.59 - gsmtp')
os.environ.get()
is setting the correct values on Heroku. Make sure you follow all the steps on support.google.com/mail/?p=BadCredentials - e.g. you don't mention the captcha suggestion in your question. You should also make sure thatEMAIL_HOST_USER
matchessender = '[email protected]'
- Gmail won't let you send email for a different account. If it still doesn't work, then I agree with Klaus that you should look for a different email provider. – Cetane