import random import string import smtplib from email.mime.text import MIMEText import os import uuid import config from werkzeug.utils import secure_filename UPLOAD_ROOT = os.path.join(os.getcwd(), 'uploads') def generate_password(length=10): characters = string.ascii_letters + string.digits return ''.join(random.choice(characters) for _ in range(length)) def send_email(recipient_email, subject, body): if config.USE_EXTERNAL_SMTP: sender_email = config.SMTP_SENDER_EMAIL sender_password = config.SMTP_SENDER_PASSWORD msg = MIMEText(body) msg['Subject'] = subject msg['From'] = sender_email msg['To'] = recipient_email try: with smtplib.SMTP(config.SMTP_SERVER, config.SMTP_PORT) as server: if config.SMTP_USE_TLS: server.starttls() server.login(sender_email, sender_password) server.send_message(msg) except Exception as e: print(f"Failed to send email via external SMTP: {e}") else: try: process = os.popen(f"/usr/sbin/sendmail -t") process.write(f"To: {recipient_email}\n") process.write(f"Subject: {subject}\n") process.write(f"\n{body}") process.close() except Exception as e: print(f"Failed to send email via local sendmail: {e}") def is_file_allowed(file): return '.' in file.filename and file.filename.rsplit('.', 1)[1].lower() in config.ALLOWED_EXTENSIONS def save_document(file, subfolder): if not is_file_allowed(file): raise ValueError("File type not allowed. Only images are permitted.") if len(file.read()) > config.MAX_FILE_SIZE: raise ValueError("File size exceeds the limit of 5 MB.") file.seek(0) upload_folder = os.path.join(UPLOAD_ROOT, subfolder) os.makedirs(upload_folder, exist_ok=True) filename = secure_filename(f"{uuid.uuid4().hex}.{file.filename.rsplit('.', 1)[1].lower()}") filepath = os.path.join(upload_folder, filename) file.save(filepath) return filename