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:
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.
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:
Create a .env file in your project directory.
Add your credentials like this: [email protected]
GMAIL_PASSWORD=your_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!