\x89PNG\r\n\x1a\n\x00\x00\x00\x0DIHDR\x00\x00\x00\x01\x00 \x00\x00\x01\x08\x06\x00\x00\x00\x1F\x15\xC4\x89\x00\x00\x00 \x0AIDATx\x9Ccb\x00\x00\x00\x06\x00\x03\x1A\x05\x9D\x00\x00 \x00\x00IEND\xAE\x42\x60\x82
| Path : /var/www/html/yedekledb24/DatabaseBackupMasterv5/ |
|
B-Con CMD Config cPanel C-Rdp D-Log Info Jump Mass Ransom Symlink vHost Zone-H |
| Current File : /var/www/html/yedekledb24/DatabaseBackupMasterv5/email_utils.py |
import os
import logging
from datetime import datetime
from flask import render_template_string
from flask_mail import Message
from app import mail
from models import BackupJob, BackupLog, DatabaseConnection, StorageTarget
from backup_utils import format_size
logger = logging.getLogger(__name__)
# HTML template for backup success email
SUCCESS_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
.container { width: 100%; max-width: 600px; margin: 0 auto; }
.header { background-color: #28a745; color: white; padding: 20px; text-align: center; }
.content { padding: 20px; }
.footer { background-color: #f4f4f4; padding: 10px; text-align: center; font-size: 12px; }
table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }
th { background-color: #f2f2f2; }
.success { color: #28a745; font-weight: bold; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h2>Backup Completed Successfully</h2>
</div>
<div class="content">
<p>Hello,</p>
<p>Your database backup job <strong>{{ job_name }}</strong> has completed successfully.</p>
<h3>Backup Details:</h3>
<table>
<tr>
<th>Database</th>
<td>{{ database_name }} ({{ database_type }})</td>
</tr>
<tr>
<th>Storage Target</th>
<td>{{ storage_name }} ({{ storage_type }})</td>
</tr>
<tr>
<th>Backup File</th>
<td>{{ backup_file }}</td>
</tr>
<tr>
<th>Backup Size</th>
<td>{{ backup_size }}</td>
</tr>
<tr>
<th>Duration</th>
<td>{{ duration }} seconds</td>
</tr>
<tr>
<th>Timestamp</th>
<td>{{ timestamp }}</td>
</tr>
<tr>
<th>Status</th>
<td class="success">Success</td>
</tr>
</table>
<p>This is an automated message. Please do not reply to this email.</p>
</div>
<div class="footer">
<p>Database Backup System © {{ current_year }}</p>
</div>
</div>
</body>
</html>
"""
# HTML template for backup failure email
FAILURE_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
.container { width: 100%; max-width: 600px; margin: 0 auto; }
.header { background-color: #dc3545; color: white; padding: 20px; text-align: center; }
.content { padding: 20px; }
.footer { background-color: #f4f4f4; padding: 10px; text-align: center; font-size: 12px; }
table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }
th { background-color: #f2f2f2; }
.failure { color: #dc3545; font-weight: bold; }
.error-message { background-color: #f8d7da; border: 1px solid #f5c6cb; color: #721c24; padding: 10px; margin: 10px 0; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h2>Backup Failed</h2>
</div>
<div class="content">
<p>Hello,</p>
<p>Your database backup job <strong>{{ job_name }}</strong> has failed.</p>
<h3>Backup Details:</h3>
<table>
<tr>
<th>Database</th>
<td>{{ database_name }} ({{ database_type }})</td>
</tr>
<tr>
<th>Storage Target</th>
<td>{{ storage_name }} ({{ storage_type }})</td>
</tr>
<tr>
<th>Timestamp</th>
<td>{{ timestamp }}</td>
</tr>
<tr>
<th>Status</th>
<td class="failure">Failed</td>
</tr>
</table>
<h3>Error Details:</h3>
<div class="error-message">
{{ error_message }}
</div>
<p>Please check your backup configuration and ensure that both the database and storage target are accessible.</p>
<p>This is an automated message. Please do not reply to this email.</p>
</div>
<div class="footer">
<p>Database Backup System © {{ current_year }}</p>
</div>
</div>
</body>
</html>
"""
def send_backup_notification(log_id, recipients=None):
"""
Send an email notification for a backup job.
Args:
log_id (int): ID of the backup log entry
recipients (list): List of email addresses to send notification to
Returns:
bool: True if email sent successfully, False otherwise
"""
try:
if not recipients:
# Get recipients from environment variable
recipients_str = os.environ.get('BACKUP_NOTIFICATION_EMAILS', '')
if not recipients_str:
logger.warning("No recipients configured for backup notifications")
return False
recipients = [email.strip() for email in recipients_str.split(',')]
# Get backup log details
backup_log = BackupLog.query.get(log_id)
if not backup_log:
logger.error(f"Backup log with ID {log_id} not found")
return False
job = BackupJob.query.get(backup_log.job_id)
if not job:
logger.error(f"Backup job not found for log ID {log_id}")
return False
db_conn = DatabaseConnection.query.get(job.database_id)
if not db_conn:
logger.error(f"Database connection not found for job ID {job.id}")
return False
storage = StorageTarget.query.get(job.storage_id)
if not storage:
logger.error(f"Storage target not found for job ID {job.id}")
return False
# Choose template based on backup status
if backup_log.status == 'success':
subject = f"Backup Successful: {job.name}"
template = SUCCESS_TEMPLATE
# Format backup size
backup_size_formatted = format_size(backup_log.backup_size) if backup_log.backup_size else "N/A"
# Prepare template context for success
context = {
'job_name': job.name,
'database_name': db_conn.name,
'database_type': db_conn.db_type,
'storage_name': storage.name,
'storage_type': storage.storage_type,
'backup_file': backup_log.backup_file,
'backup_size': backup_size_formatted,
'duration': f"{backup_log.duration:.2f}" if backup_log.duration else "N/A",
'timestamp': backup_log.timestamp.strftime("%Y-%m-%d %H:%M:%S UTC"),
'current_year': datetime.now().year
}
else:
subject = f"Backup Failed: {job.name}"
template = FAILURE_TEMPLATE
# Prepare template context for failure
context = {
'job_name': job.name,
'database_name': db_conn.name,
'database_type': db_conn.db_type,
'storage_name': storage.name,
'storage_type': storage.storage_type,
'error_message': backup_log.message,
'timestamp': backup_log.timestamp.strftime("%Y-%m-%d %H:%M:%S UTC"),
'current_year': datetime.now().year
}
# Render HTML content
html_content = render_template_string(template, **context)
# Use Flask-Mail
try:
# Create message
msg = Message(
subject=subject,
recipients=recipients,
html=html_content
)
# Send email
mail.send(msg)
logger.info(f"Backup notification email sent via SMTP for job {job.name}")
return True
except Exception as mail_err:
logger.error(f"SMTP email delivery failed: {str(mail_err)}")
return False
except Exception as e:
logger.error(f"Failed to send backup notification email: {str(e)}")
return False
def send_test_email(recipients, email_service=None):
"""
Send a test email to verify email configuration.
Args:
recipients (list): List of email addresses to send test email to
email_service (str): Not used (retained for backward compatibility)
Returns:
bool: True if email sent successfully, False otherwise
"""
try:
subject = "Database Backup System - Test Email"
html_content = """
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
.container { width: 100%; max-width: 600px; margin: 0 auto; }
.header { background-color: #007bff; color: white; padding: 20px; text-align: center; }
.content { padding: 20px; }
.footer { background-color: #f4f4f4; padding: 10px; text-align: center; font-size: 12px; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h2>Test Email</h2>
</div>
<div class="content">
<p>Hello,</p>
<p>This is a test email from your Database Backup System.</p>
<p>If you received this email, your email notification settings are working correctly.</p>
<p>This is an automated message. Please do not reply to this email.</p>
</div>
<div class="footer">
<p>Database Backup System © """ + str(datetime.now().year) + """</p>
</div>
</div>
</body>
</html>
"""
# Use Flask-Mail
try:
# Create message
msg = Message(
subject=subject,
recipients=recipients,
html=html_content
)
# Send email
mail.send(msg)
logger.info(f"Test email sent via SMTP to {', '.join(recipients)}")
return True
except Exception as mail_err:
logger.error(f"SMTP test email delivery failed: {str(mail_err)}")
return False
except Exception as e:
logger.error(f"Failed to send test email: {str(e)}")
return False