Files
pilates-platform/send_email.py
2025-12-09 17:50:01 +01:00

176 lines
5.3 KiB
Python

#!/usr/bin/env python3
"""
Script Python per invio email SMTP
Legge le credenziali da config.php e invia email tramite Gmail
Log solo in caso di errore
"""
import sys
import json
import re
import smtplib
import logging
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from pathlib import Path
from datetime import datetime
# Configura logging solo per errori
log_file = Path(__file__).parent / 'logs' / 'email_errors.log'
log_file.parent.mkdir(exist_ok=True)
logging.basicConfig(
filename=str(log_file),
level=logging.ERROR,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
def parse_php_config(config_path):
"""Estrae le configurazioni SMTP dal file config.php"""
config = {}
try:
with open(config_path, 'r', encoding='utf-8') as f:
content = f.read()
# Estrai le define con regex
patterns = {
'SMTP_HOST': r"define\('SMTP_HOST',\s*'([^']+)'\)",
'SMTP_PORT': r"define\('SMTP_PORT',\s*(\d+)\)",
'SMTP_USERNAME': r"define\('SMTP_USERNAME',\s*'([^']+)'\)",
'SMTP_PASSWORD': r"define\('SMTP_PASSWORD',\s*'([^']+)'\)",
'SMTP_ENCRYPTION': r"define\('SMTP_ENCRYPTION',\s*'([^']+)'\)",
'MAIL_FROM': r"define\('MAIL_FROM',\s*'([^']+)'\)",
'MAIL_FROM_NAME': r"define\('MAIL_FROM_NAME',\s*'([^']+)'\)",
}
for key, pattern in patterns.items():
match = re.search(pattern, content)
if match:
value = match.group(1)
# Converti porta in intero
if key == 'SMTP_PORT':
config[key] = int(value)
else:
config[key] = value
return config
except Exception as e:
print(json.dumps({
'success': False,
'error': f'Errore lettura config.php: {str(e)}'
}))
sys.exit(1)
def send_email(to_email, subject, html_body, config):
"""Invia email tramite SMTP"""
try:
# Crea messaggio
msg = MIMEMultipart('alternative')
msg['From'] = f"{config['MAIL_FROM_NAME']} <{config['MAIL_FROM']}>"
msg['To'] = to_email
msg['Subject'] = subject
# Aggiungi corpo HTML
html_part = MIMEText(html_body, 'html', 'utf-8')
msg.attach(html_part)
# Connetti al server SMTP
if config['SMTP_ENCRYPTION'] == 'ssl':
# SSL diretto (porta 465)
server = smtplib.SMTP_SSL(config['SMTP_HOST'], config['SMTP_PORT'], timeout=30)
else:
# TLS con STARTTLS (porta 587)
server = smtplib.SMTP(config['SMTP_HOST'], config['SMTP_PORT'], timeout=30)
server.ehlo()
server.starttls()
server.ehlo()
# Login
server.login(config['SMTP_USERNAME'], config['SMTP_PASSWORD'])
# Invia email
server.send_message(msg)
server.quit()
return {
'success': True,
'message': f'Email inviata con successo a {to_email}'
}
except smtplib.SMTPAuthenticationError as e:
error_msg = f'Autenticazione SMTP fallita per {to_email}: {str(e)}'
logging.error(error_msg)
return {
'success': False,
'error': error_msg
}
except smtplib.SMTPException as e:
error_msg = f'Errore SMTP invio a {to_email}: {str(e)}'
logging.error(error_msg)
return {
'success': False,
'error': error_msg
}
except Exception as e:
error_msg = f'Errore generico invio a {to_email}: {str(e)}'
logging.error(error_msg)
return {
'success': False,
'error': error_msg
}
def main():
"""Funzione principale"""
if len(sys.argv) < 2:
print(json.dumps({
'success': False,
'error': 'Uso: python send_email.py <json_data>'
}))
sys.exit(1)
try:
# Parse input JSON
data = json.loads(sys.argv[1])
if 'to' not in data or 'subject' not in data or 'html' not in data:
error = 'Parametri mancanti: to, subject, html sono obbligatori'
logging.error(error)
print(json.dumps({
'success': False,
'error': error
}))
sys.exit(1)
# Leggi configurazione
script_dir = Path(__file__).parent
config_path = script_dir / 'includes' / 'config.php'
config = parse_php_config(config_path)
# Invia email
result = send_email(data['to'], data['subject'], data['html'], config)
print(json.dumps(result))
sys.exit(0 if result['success'] else 1)
except json.JSONDecodeError as e:
error = f'JSON non valido: {str(e)}'
logging.error(error)
print(json.dumps({
'success': False,
'error': error
}))
sys.exit(1)
except Exception as e:
error = f'Errore: {str(e)}'
logging.error(error)
print(json.dumps({
'success': False,
'error': error
}))
sys.exit(1)
if __name__ == '__main__':
main()