Files
booking/utils.py
T

71 lines
2.6 KiB
Python
Raw Normal View History

2025-01-12 09:57:35 +08:00
import random
import string
import smtplib
from email.mime.text import MIMEText
2025-01-21 20:45:29 +08:00
import os
import uuid
import config
2025-02-25 17:07:35 +08:00
import subprocess
2025-01-21 20:45:29 +08:00
from werkzeug.utils import secure_filename
2025-02-16 20:22:30 +08:00
from app import logger
2025-01-21 20:45:29 +08:00
UPLOAD_ROOT = os.path.join(os.getcwd(), 'uploads')
2025-01-12 09:57:35 +08:00
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):
2025-01-28 12:33:38 +08:00
if config.USE_EXTERNAL_SMTP:
sender_email = config.SMTP_SENDER_EMAIL
sender_password = config.SMTP_SENDER_PASSWORD
2025-01-12 09:57:35 +08:00
2025-01-28 12:33:38 +08:00
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = recipient_email
2025-01-12 09:57:35 +08:00
2025-01-28 12:33:38 +08:00
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)
2025-02-16 20:22:30 +08:00
logger.info(f"Email sent successfully via SMTP to {recipient_email}")
2025-01-28 12:33:38 +08:00
except Exception as e:
2025-02-16 20:22:30 +08:00
logger.error(f"Failed to send email via SMTP to {recipient_email}: {e}")
2025-01-28 12:33:38 +08:00
else:
try:
2025-02-25 17:07:35 +08:00
process = subprocess.Popen(
["/usr/sbin/sendmail", "-t"],
stdin=subprocess.PIPE,
stderr=subprocess.PIPE
)
email_message = f"To: {recipient_email}\nSubject: {subject}\n\n{body}"
stdout, stderr = process.communicate(input=email_message.encode())
if process.returncode != 0:
logger.error(f"Sendmail error: {stderr.decode().strip()}")
else:
logger.info(f"Email sent successfully via sendmail to {recipient_email}")
2025-01-28 12:33:38 +08:00
except Exception as e:
2025-02-16 20:22:30 +08:00
logger.error(f"Failed to send email via local sendmail to {recipient_email}: {e}")
2025-01-21 20:45:29 +08:00
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