This Python script connects to a Gmail account via IMAP, retrieves the latest email from the inbox, and extracts a 6-digit (you can change it as you wish ofc) verification code from the email's body. This is useful for automating processes that require verification codes sent via email.
- Python 3.x
imaplib
(standard library)email
(standard library)re
(standard library)
Note: If using Gmail use an app-specific password if two-factor authentication (2FA) is enabled if not do the 2FA it's good for you.
-
Install Dependencies
This script uses only standard Python libraries, so no additional installation is needed.
-
Configure the Script
- Set
mail
andpassword
variables in themain()
function with your email address and password respectively.
def main(): mail = "[email protected]" password = "your_password" get_verification_code(mail, password)
- Set
-
Save the script to a file, e.g.,
extract_verification_code.py
. -
Run the script using Python:
pip install requirements.txt python extract_verification_code.py
- Connects to the Gmail IMAP server.
- Logs in using provided email credentials.
- Selects the inbox folder.
- Searches for the latest email.
- Fetches the email body.
- Extracts a 6-digit verification code using a regular expression.
- Do not hardcode your email and password in the script. Consider using environment variables or secure credential storage.
- Use app-specific passwords or OAuth 2.0 for Gmail to enhance security.
This script is provided as-is, without any warranties. Feel free to use and modify it as needed.
Make sure to replace "[email protected]"
and "your_password"
in the main()
function with your actual email credentials or configure a more secure method to handle credentials.