How to store Gmail login info in a Python script?

Hey everyone, I’m trying to figure out how to save my Gmail login details in my Python code. Right now, I have to type them in every time I run the script, which is a pain. Here’s what my current setup looks like:

import smtplib
from getpass import getpass

username = input('What\'s your Gmail username? ')
password = getpass('Type your password: ')
sender = input('Who\'s the email from? ')

# Rest of the code here

Is there a way to make this automatic? I’d love to just run the script without having to enter all this stuff each time. Any ideas on how to do this safely? Thanks in advance for your help!

While storing credentials directly in your script or a plain text file isn’t recommended, you might want to consider using Python’s built-in ‘keyring’ module. It securely stores your passwords in your system’s keychain or credential vault. Here’s how you could implement it:

import keyring

Set the password (you only need to do this once)

keyring.set_password(‘gmail’, ‘[email protected]’, ‘your_password’)

Retrieve the password in your script

username = ‘[email protected]
password = keyring.get_password(‘gmail’, username)

This method is more secure than storing passwords in plain text, and it’s still convenient as you don’t need to input credentials each time. Just remember to install the keyring library first with ‘pip install keyring’. It’s a good balance between security and ease of use for personal projects.

hey, have u tried using a config file? just make a simple text file with ur login info and read it in ur script. like this:

with open(‘config.txt’, ‘r’) as f:
username = f.readline().strip()
password = f.readline().strip()

not super secure but way easier than typing it everytime lol

I’ve faced this issue before, and I can share what worked for me. While it’s tempting to hardcode credentials, it’s not secure. Instead, I use environment variables. Here’s how:

  1. Create a .env file in your project directory.

  2. Add your credentials like this:
    [email protected]
    GMAIL_PASSWORD=your_password

  3. Install the python-dotenv package.

  4. In your script, load the variables:

import os
from dotenv import load_dotenv

load_dotenv()

username = os.getenv(‘GMAIL_USERNAME’)
password = os.getenv(‘GMAIL_PASSWORD’)

This way, your credentials remain separate from your code, making it safer if you share your script or use version control. Don’t forget to add .env to your .gitignore file if you’re using Git. Hope this helps!