In this article, you’ll explore some exciting Python tricks that can save you time, increase productivity, and make your coding journey more enjoyable.
You’ll discover how to schedule emails so you never forget an important message, encrypt and decrypt sensitive information, retrieve saved Wi-Fi passwords on Linux when needed, and instantly share files from a folder using Python’s built-in tools.
You’ll also learn how to schedule Python scripts to run automatically at specific times and how to record audio from your microphone. Let’s dive in!
Automate Email Sending on a Schedule
With just a few lines of code, you can schedule emails to be sent automatically at any time.
Let’s say you want to send a report every morning at 9 AM. To do that, you can use the schedule module, which you need to install first. Open your terminal or command prompt and run:
pip install schedule
Then, add the following code:
import schedule
import time
import smtplib
EMAIL_ADDRESS = "your_email@gmail.com"
EMAIL_PASSWORD = "your_password"
def send_email():
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
server.sendmail(
EMAIL_ADDRESS,
"recipient@example.com",
"Subject: Daily Update\n\nHere is your scheduled email!"
)
print("Email sent!")
# Schedule the email to be sent at 9 AM every day
schedule.every().day.at("09:00").do(send_email)
# Keep checking for scheduled tasks
while True:
schedule.run_pending()
time.sleep(60)
This code will send an email every day at 9 AM automatically.
Send Emails to Multiple Recipients
Sending an email to one person is easy, but what if you need to send the same message to multiple recipients? Whether it’s a newsletter, a team update, or a bulk notification, Python makes it simple.
Add the following code:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Your email credentials
EMAIL_ADDRESS = "your_email@gmail.com"
EMAIL_PASSWORD = "your_password"
# List of recipients
recipients = ["user1@example.com", "user2@example.com", "user3@example.com"]
# Create the email message
msg = MIMEMultipart()
msg["From"] = EMAIL_ADDRESS
msg["To"] = ", ".join(recipients) # Join multiple emails
msg["Subject"] = "Team Update 📢"
# Email body
body = (
"Hello Team,\n\n"
"This is an automated email sent to multiple recipients.\n\n"
"Best Regards,\n"
"Python Bot"
)
msg.attach(MIMEText(body, "plain"))
# Send the email
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls() # Secure the connection
server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
server.sendmail(EMAIL_ADDRESS, recipients, msg.as_string())
print("Email sent successfully to multiple recipients!")
You need to add multiple emails to the list line: recipients = [“user1@example.com”, “user2@example.com”, “user3@example.com”]. Now, you can efficiently send emails to multiple people.
Encrypt and Decrypt a Message
To encrypt a message, you can use Fernet. Before using Fernet, install the cryptography package:
pip install cryptography
Add the following code:
from cryptography.fernet import Fernet
# Generate a key for encryption
key = Fernet.generate_key()
cipher = Fernet(key)
# Encrypt the message
message = "Hello, this is a secret message!"
encrypted_message = cipher.encrypt(message.encode())
# Decrypt the message
decrypted_message = cipher.decrypt(encrypted_message).decode()
# Display results
print(f"Original Message: {message}")
print(f"Encrypted Message: {encrypted_message}")
print(f"Decrypted Message: {decrypted_message}")
print(f"Encryption Key: {key}")
This Python code uses Fernet encryption to securely hide a message. It starts by generating a unique secret key and then uses that key to encrypt a simple message. After that, it decrypts the message back to its original form using the same key.
Get Saved Wi-Fi Passwords on Linux
Ever forgotten your Wi-Fi password and don’t feel like resetting it? No worries! If your Linux system has connected to the Wi-Fi before, you can retrieve the saved password using Python in just a few lines of code.
On Linux, Wi-Fi passwords are stored in NetworkManager’s configuration files, located in:/etc/NetworkManager/system-connections.
Each saved Wi-Fi network has its own file in this directory, and the password is stored under psk= Here’s how you can use Python to extract Wi-Fi passwords from your system:
import os
# Run a shell command to list all saved Wi-Fi passwords
os.system("sudo cat /etc/NetworkManager/system-connections/* | grep psk=")
The command “sudo cat /etc/NetworkManager/system-connections/* reads all Wi-Fi config files and “grep psk=” filters out only the saved Wi-Fi passwords.
With this simple Python trick, you can quickly retrieve saved Wi-Fi passwords on Linux without digging through settings. Whether you need to share a forgotten password with a friend or reconnect a new device, this can save you some time.
Instantly Share Files in a Directory with Python
Python has a built-in way to host a simple web server using the http.server module. This lets anyone on the network download files via a web browser. Open the terminal and run this command:
python3 -m http.server 8080
The current directory becomes publicly accessible where people on the same network can visit “http://your-ip:8080” in a browser to see and download files.
Share Files from a Specific Folder
Instead of sharing the current folder, specify a directory:
python3 -m http.server 8080 --directory ~/Downloads
Now, only files in the Downloads folder are accessible.
Run a Python Script at a Specific Time
The schedule library allows you to run a Python function at a certain time without needing external tools.
Add the following code:
import schedule
import time
def my_script():
print("Running my script! 🚀")
# Schedule the function to run at 9:00 AM
schedule.every().day.at("09:00").do(my_script)
print("⏳ Waiting for the scheduled time...")
while True:
schedule.run_pending()
time.sleep(1) # Wait a bit before checking again
This Python code runs my_script every day at 9:00 AM using the schedule library.
Record Audio from Your Microphone
Ever wanted to record audio using Python? Whether you’re building a voice assistant, saving meeting notes, or just having fun, Python makes it super easy to capture sound from your microphone and save it as a file.
Python doesn’t have built-in microphone access, so you need the sounddevice library.
pip install sounddevice numpy scipy
Then, add the following code:
import sounddevice as sd
from scipy.io.wavfile import write
# Settings
RATE = 44100 # Sample rate
DURATION = 5 # Seconds
OUTPUT_FILE = "audio_output.wav"
print("🎙️ Recording... Speak now!")
audio_data = sd.rec(int(DURATION * RATE), samplerate=RATE, channels=1, dtype='int16')
sd.wait() # Wait until recording is finished
# Save the file
write(OUTPUT_FILE, RATE, audio_data)
print(f"✅ Recording finished! Saved as {OUTPUT_FILE}")
This Python script records audio from the microphone for five seconds and saves it as a WAV file.
Bottom Line
Whether you’re using Python to automate tasks or just explore new possibilities, the key is to keep experimenting and learning. The more you dive into Python’s capabilities, the more you’ll realize how powerful and flexible it truly is.
Thank you!