How to store Gmail login info in a Python script?

Hey everyone! I’m working on a Python script that needs to access my Gmail account. Right now, it asks for my username and password every time I run it. That’s kind of annoying. Is there a way to save my login info in the script so I don’t have to type it in each time?

Here’s a bit of my current code:

import random
import smtplib

email = input('What's your Gmail address? ')
password = input('Type your password: ')
sender = input('Who sent the email you want to check? ')

# Rest of the code...

I know it’s not super safe, but this is just for my personal use. Any ideas on how to make this more convenient? Thanks!

I’ve faced this issue before, and while storing credentials directly in your script isn’t ideal, there are safer alternatives. One approach is to create a separate configuration file (for example, config.ini) to store your email and password and then use Python’s configparser module to read this file.

You can start by creating a config.ini file with your credentials, then in your script, import configparser to load the file and retrieve the credentials as needed. This method keeps your sensitive info separate from your main code and is an improvement over hardcoding the credentials or repeatedly entering them manually. Just be sure to add config.ini to your .gitignore if you’re using version control.

For added security, consider switching to environment variables or a dedicated secrets management tool if your project scales beyond personal use.

hey there! i’ve had the same issue. one easy way is to use a .env file for your login info. just create a file called .env in your project folder and put your email and password there like this:

[email protected]
PASSWORD=yourpassword

then use the python-dotenv library to load it. it’s pretty simple and keeps your login separate from your main code.

While it’s tempting to hardcode credentials for convenience, it’s generally not recommended. A more secure approach is using OAuth 2.0 for Gmail API access. This method eliminates the need to store your password and provides better security overall.

To implement OAuth 2.0, you’ll need to set up a project in the Google Cloud Console, enable the Gmail API, and obtain the necessary credentials. Then, use a library like google-auth-oauthlib to handle the authentication flow.

This approach may seem more complex initially, but it offers better security and adheres to best practices. It also allows you to manage access without exposing your actual Gmail password. Remember to store your client secrets securely and never commit them to version control.