How to configure SMTP settings for sending emails through Gmail with Python

I’ve been using Gmail’s web interface for checking my emails, but now I need to create a Python script that can send emails programmatically. I’m having trouble figuring out the correct SMTP server configuration for Gmail.

Here’s what I’m trying to do:

import smtplib

# Need help with these settings
email_server = smtplib.SMTP('what_hostname_goes_here?', 'which_port_number?')
email_server.login('[email protected]', 'mypassword')

I’m not sure what hostname and port number I should use for Gmail’s SMTP server. Can someone help me with the correct configuration?

Thanks in advance!

don’t forget to turn on “less secure app access” in your Google account if you’re not using 2FA - Gmail will block the connection otherwise. this exact thing happened to me last week and I was pulling my hair out until I found that setting.

The hostname is smtp.gmail.com with port 587 for TLS encryption. It’s crucial to enable two-factor authentication on your Google account and generate an App Password for use in your script, as regular Gmail passwords no longer work for security reasons. Additionally, remember to call email_server.starttls() before the login method to establish an encrypted connection. This was a lesson I learned after my script repeatedly failed authentication until I switched to using app passwords.

Gmail’s rate limiting caught me off guard when I started sending emails programmatically. Even with smtp.gmail.com and port 587 configured correctly, Google throttles you if you send too many emails too fast. During testing, I kept getting temporary auth failures that weren’t related to my app password setup at all. Add delays between sends when processing multiple emails - Gmail will temporarily block your script even with valid credentials if you don’t.

Just a heads up - Google killed the “less secure app access” option in May 2022, so you won’t find that setting anymore. Hit this same wall when I was updating an old email script. You’ll need App Passwords with 2FA turned on now - that’s pretty much your only option. Don’t forget to add email_server.quit() at the end to properly close the SMTP session. I’ve had scripts that tested fine but broke in production because they weren’t cleaning up connections.

for Gmail, you’ll use smtp.gmail.com and port 587. also, regular passwords won’t work. generate an app password from your Google account settings to authenticate.