Search code examples
djangoauthenticationgmail

Django Gmail auth fails despite correct credentials


My sending mail from django through gmail suddenly stopped working. It was working fine for over a year now, so I assume my basic setup should still be fine. The Google Account in question has 2FA enabled and the password used in the config below is a generated app-password, not the main accuont password. I already logged into Gmail via browser and checked that it hasn't been locked and that it isn't over quota.

settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587 
EMAIL_HOST_USER = '<MY-MAIL-ADDRESS>'
EMAIL_HOST_PASSWORD = '<PASSWORD>'
DEFAULT_FROM_EMAIL = '<MY-MAIL-ADDRESS>'

I already verified my credentials by using the command below: (ofc shell expansion doesn't work i just pasted the output of the command at that location)

$ openssl s_client -connect smtp.gmail.com:587 -starttls smtp
>AUTH PLAIN $(echo -ne '\0MY-MAIL-ADDRESS\0PASSWORD' | base64)
>235 2.7.0 Accepted

However, if I try to use send_mail it bounces:

In [1]: from django.core.mail import send_mail                                                                                                                           
                                                                                                                                                                         
In [2]: send_mail('Subject', 'This is a test message', 'MY-MAIL-ADDRESS', ('[email protected]',))  
 (Output shortened)
SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials r17sm9826202wmq.5 - gsmtp')

Any hints on what might (suddenly) be wrong?


Solution

  • As it turns out, we were blacklisted by Google.

    I added my webserver to the IP-Whitelist using this guide. After that, mails started working again.

    Interestingly enough, even supporters at Google (for a paid Google Workspace account, not free gmail) weren't able to tell me this, I had to experiment myself