Gmail SMTP Authentication Fails on Railway Deployment with Django

I’m having trouble with email sending through Gmail when my Django app is deployed on Railway. The error shows up in the deployment logs and it’s really frustrating because everything works perfectly on my local machine and even on my EC2 server.

The main error I’m getting is:

smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. For more information, go to 5.7.8 https://support.google.com/mail/?p=BadCredentials')

Here’s my email configuration in Django settings:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = config('MY_EMAIL_USER')
EMAIL_HOST_PASSWORD = config('MY_EMAIL_PASS')

I’m using an app-specific password that I created in my Gmail account settings, not my regular password. This same setup works fine locally and on other hosting platforms. Has anyone encountered this issue with Railway specifically? What could be different about Railway’s environment that would cause Gmail authentication to fail?

Same thing happened to me with Railway last month. Gmail’s security flagged the login as suspicious because Railway uses shared IPs. Even though app passwords normally work fine, Gmail treats cloud hosting IPs differently than your local machine. Here’s what worked: I temporarily turned on “Less secure app access” in Gmail, sent one test email through Railway, then turned it back off and switched to the app password again. This whitelists Railway’s IP with Gmail. Also check your environment variables in Railway’s dashboard - their parsing gets weird with special characters.

railway’s probably blocking smtp ports or gmail flagged their ip range. switch to port 465 with ssl instead of tls - works better on most cloud platforms. also check your env variables in railway’s console. i’ve seen them not match what you set locally.

There are several factors that could be affecting your SMTP authentication with Gmail on Railway. Firstly, confirm whether Railway restricts outbound traffic on port 587, as this is a common issue with certain platforms. Additionally, Gmail may be rejecting requests from Railway’s IP addresses if they have a record of unusual activity. It might be worth creating a new app-specific password for this deployment, just in case the existing one is being rejected for some reason. If you continue to face issues, consider switching to a more reliable email service like SendGrid or Mailgun, which can streamline your email sending process.