64 lines
2.3 KiB
Python
64 lines
2.3 KiB
Python
import random
|
|
import string
|
|
import smtplib
|
|
from email.mime.text import MIMEText
|
|
import os
|
|
import uuid
|
|
import config
|
|
from werkzeug.utils import secure_filename
|
|
from app import logger
|
|
|
|
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)
|
|
logger.info(f"Email sent successfully via SMTP to {recipient_email}")
|
|
except Exception as e:
|
|
logger.error(f"Failed to send email via SMTP to {recipient_email}: {e}")
|
|
else:
|
|
try:
|
|
process = os.popen("/usr/sbin/sendmail -t")
|
|
process.write(f"To: {recipient_email}\n")
|
|
process.write(f"Subject: {subject}\n")
|
|
process.write(f"\n{body}")
|
|
process.close()
|
|
logger.info(f"Email sent successfully via sendmail to {recipient_email}")
|
|
except Exception as e:
|
|
logger.error(f"Failed to send email via local sendmail to {recipient_email}: {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 |