first commit

This commit is contained in:
Jack Cheang
2025-06-19 15:34:30 +08:00
commit cd91bcffda
5 changed files with 194 additions and 0 deletions

View File

@@ -0,0 +1,8 @@
# SMTP Configuration
SMTP_SERVER=smtp.example.com
SMTP_PORT=587
SMTP_USERNAME=your_username@example.com
SMTP_PASSWORD=your_password
SMTP_FROM=your_email@example.com
SMTP_TO=recipient@example.com
SMTP_USE_TLS=True

65
email-smtp-tester/.gitignore vendored Normal file
View File

@@ -0,0 +1,65 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# Environment variables
.env
.env.*
!.env.example
# Logs
logs/
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Database
*.db
*.sqlite3
*.sqlite
# IDE
.idea/
.vscode/
*.swp
*.swo
*~
# Local development
local_settings.py
# Testing
.coverage
htmlcov/
.pytest_cache/
# Virtual Environment
.venv/
venv/
ENV/
# Distribution / packaging
dist/
build/
*.egg-info/
*.egg

View File

@@ -0,0 +1,2 @@
python-dotenv==1.0.0
secure-smtplib==0.1.1

View File

@@ -0,0 +1,110 @@
import os
import smtplib
import logging
from datetime import datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from dotenv import load_dotenv
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(),
logging.FileHandler('email_sender.log')
]
)
logger = logging.getLogger(__name__)
def send_email(subject, body):
# Start logging
logger.info("="*50)
logger.info(f"Starting email sending process at {datetime.now()}")
logger.info("-"*50)
try:
# Load environment variables
load_dotenv()
logger.info("Environment variables loaded successfully")
# Email configuration
smtp_server = os.getenv('SMTP_SERVER')
smtp_port = int(os.getenv('SMTP_PORT', '587'))
smtp_username = os.getenv('SMTP_USERNAME')
smtp_password = os.getenv('SMTP_PASSWORD')
from_email = os.getenv('SMTP_FROM')
to_email = os.getenv('SMTP_TO')
use_tls = os.getenv('SMTP_USE_TLS', 'True').lower() == 'true'
# Log configuration
logger.info(f"SMTP Server: {smtp_server}:{smtp_port}")
logger.info(f"From: {from_email}")
logger.info(f"To: {to_email}")
logger.info(f"Use TLS: {use_tls}")
logger.info(f"Subject: {subject}")
logger.debug(f"Email body: {body}")
# Create message
logger.info("Creating email message...")
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
logger.debug("Email message created successfully")
# Create SMTP session
logger.info(f"Connecting to SMTP server: {smtp_server}:{smtp_port}")
with smtplib.SMTP(smtp_server, smtp_port, timeout=30) as server:
logger.info("SMTP connection established")
if use_tls:
logger.info("Starting TLS encryption...")
server.starttls()
logger.info("TLS encryption started")
# Login to SMTP server
logger.info("Authenticating with SMTP server...")
try:
server.login(smtp_username, smtp_password)
logger.info("Successfully authenticated with SMTP server")
except Exception as auth_error:
logger.error(f"SMTP authentication failed: {str(auth_error)}")
logger.error(f"Username used: {smtp_username}")
raise
# Send email
logger.info("Sending email...")
server.send_message(msg)
logger.info("Email sent successfully!")
logger.info(f"Email details - From: {from_email}, To: {to_email}, Subject: {subject}")
return True
except smtplib.SMTPException as smtp_error:
logger.error(f"SMTP Error occurred: {str(smtp_error)}")
logger.error(f"SMTP Error code: {getattr(smtp_error, 'smtp_code', 'N/A')}")
logger.error(f"SMTP Error message: {getattr(smtp_error, 'smtp_error', 'N/A')}")
return False
except Exception as e:
logger.error(f"Unexpected error occurred: {str(e)}", exc_info=True)
return False
finally:
logger.info("="*50 + "\n")
if __name__ == "__main__":
try:
# Test email
subject = "SMTP Test Email"
body = "This is a test email sent using Python's smtplib with SMTP on port 587."
logger.info("Starting email test...")
result = send_email(subject, body)
if result:
logger.info("Email test completed successfully!")
else:
logger.error("Email test failed!")
except Exception as e:
logger.critical(f"Critical error in main: {str(e)}", exc_info=True)

9
email-smtp-tester/start.sh Executable file
View File

@@ -0,0 +1,9 @@
#!/bin/bash
set -e
source .env
python3.13 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
exec python3.13 send_email.py