Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(email): commit serverkit-email extension backend

Juan Denisd482c6d2619e
diff --git a/backend/app/plugins/serverkit-email/__init__.py b/backend/app/plugins/serverkit-email/__init__.py
new file mode 100644
index 00000000..51e67b6d
--- /dev/null
+++ b/backend/app/plugins/serverkit-email/__init__.py
@@ -0,0 +1 @@
+"""ServerKit Email extension backend package."""
diff --git a/backend/app/plugins/serverkit-email/dkim_service.py b/backend/app/plugins/serverkit-email/dkim_service.py
new file mode 100644
index 00000000..d705a7f8
--- /dev/null
+++ b/backend/app/plugins/serverkit-email/dkim_service.py
@@ -0,0 +1,270 @@
+"""OpenDKIM management service for DKIM signing."""
+import os
+import re
+import subprocess
+from typing import Dict
+
+from app.utils.system import PackageManager, ServiceControl, run_privileged
+
+
+class DKIMService:
+ """Service for managing OpenDKIM (DKIM email signing)."""
+
+ OPENDKIM_CONF = '/etc/opendkim.conf'
+ OPENDKIM_DIR = '/etc/opendkim'
+ OPENDKIM_KEYS_DIR = '/etc/opendkim/keys'
+ KEY_TABLE = '/etc/opendkim/KeyTable'
+ SIGNING_TABLE = '/etc/opendkim/SigningTable'
+ TRUSTED_HOSTS = '/etc/opendkim/TrustedHosts'
+
+ OPENDKIM_CONF_CONTENT = """# OpenDKIM configuration - Managed by ServerKit
+Syslog yes
+SyslogSuccess yes
+LogWhy yes
+Canonicalization relaxed/simple
+Mode sv
+SubDomains no
+AutoRestart yes
+AutoRestartRate 10/1M
+Background yes
+DNSTimeout 5
+SignatureAlgorithm rsa-sha256
+KeyTable refile:/etc/opendkim/KeyTable
+SigningTable refile:/etc/opendkim/SigningTable
+ExternalIgnoreList /etc/opendkim/TrustedHosts
+InternalHosts /etc/opendkim/TrustedHosts
+Socket inet:8891@localhost
+PidFile /run/opendkim/opendkim.pid
+OversignHeaders From
+UserID opendkim
+UMask 007
+"""
+
+ TRUSTED_HOSTS_DEFAULT = """# Trusted hosts - Managed by ServerKit
+127.0.0.1
+::1
+localhost
+"""
+
+ @classmethod
+ def get_status(cls) -> Dict:
+ """Get OpenDKIM installation and running status."""
+ installed = False
+ running = False
+ enabled = False
+ version = None
+ try:
+ result = subprocess.run(['which', 'opendkim'], capture_output=True, text=True)
+ installed = result.returncode == 0
+ if not installed:
+ installed = PackageManager.is_installed('opendkim')
+ if installed:
+ running = ServiceControl.is_active('opendkim')
+ enabled = ServiceControl.is_enabled('opendkim')
+ result = subprocess.run(['opendkim', '-V'], capture_output=True, text=True, stderr=subprocess.STDOUT)
+ match = re.search(r'OpenDKIM\s+Filter\s+v(\S+)', result.stdout)
+ if match:
+ version = match.group(1)
+ except (subprocess.SubprocessError, FileNotFoundError):
+ pass
+
+ return {
+ 'installed': installed,
+ 'running': running,
+ 'enabled': enabled,
+ 'version': version,
+ }
+
+ @classmethod
+ def install(cls) -> Dict:
+ """Install OpenDKIM."""
+ try:
+ result = PackageManager.install(['opendkim', 'opendkim-tools'], timeout=300)
+ if result.returncode != 0:
+ return {'success': False, 'error': result.stderr or 'Failed to install OpenDKIM'}
+
+ # Create directories
+ run_privileged(['mkdir', '-p', cls.OPENDKIM_KEYS_DIR])
+ run_privileged(['chown', '-R', 'opendkim:opendkim', cls.OPENDKIM_DIR])
+
+ # Create config files
+ run_privileged(['tee', cls.OPENDKIM_CONF], input=cls.OPENDKIM_CONF_CONTENT)
+ run_privileged(['tee', cls.TRUSTED_HOSTS], input=cls.TRUSTED_HOSTS_DEFAULT)
+ run_privileged(['touch', cls.KEY_TABLE])
+ run_privileged(['touch', cls.SIGNING_TABLE])
+
+ # Set permissions
+ run_privileged(['chown', '-R', 'opendkim:opendkim', cls.OPENDKIM_DIR])
+ run_privileged(['chmod', '700', cls.OPENDKIM_KEYS_DIR])
+
+ # Create PID directory
+ run_privileged(['mkdir', '-p', '/run/opendkim'])
+ run_privileged(['chown', 'opendkim:opendkim', '/run/opendkim'])
+
+ # Add postfix to opendkim group
+ run_privileged(['usermod', '-aG', 'opendkim', 'postfix'])
+
+ ServiceControl.enable('opendkim')
+ ServiceControl.start('opendkim', timeout=30)
+
+ return {'success': True, 'message': 'OpenDKIM installed successfully'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def generate_key(cls, domain: str, selector: str = 'default') -> Dict:
+ """Generate DKIM key pair for a domain."""
+ try:
+ key_dir = os.path.join(cls.OPENDKIM_KEYS_DIR, domain)
+ run_privileged(['mkdir', '-p', key_dir])
+
+ # Generate key
+ result = run_privileged([
+ 'opendkim-genkey',
+ '-s', selector,
+ '-d', domain,
+ '-D', key_dir,
+ '-b', '2048',
+ ])
+ if result.returncode != 0:
+ return {'success': False, 'error': result.stderr or 'Key generation failed'}
+
+ # Set permissions
+ run_privileged(['chown', '-R', 'opendkim:opendkim', key_dir])
+ run_privileged(['chmod', '600', os.path.join(key_dir, f'{selector}.private')])
+
+ # Read the public key TXT record
+ txt_file = os.path.join(key_dir, f'{selector}.txt')
+ result = run_privileged(['cat', txt_file])
+ public_key_record = result.stdout.strip() if result.returncode == 0 else ''
+
+ # Extract just the key value from the TXT record
+ key_match = re.search(r'p=([A-Za-z0-9+/=\s]+)', public_key_record)
+ public_key = key_match.group(1).replace(' ', '').replace('\n', '').replace('\t', '').replace('"', '') if key_match else ''
+
+ return {
+ 'success': True,
+ 'domain': domain,
+ 'selector': selector,
+ 'private_key_path': os.path.join(key_dir, f'{selector}.private'),
+ 'public_key': public_key,
+ 'dns_record': public_key_record,
+ 'dns_name': f'{selector}._domainkey.{domain}',
+ 'dns_value': f'v=DKIM1; k=rsa; p={public_key}',
+ }
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def add_domain(cls, domain: str, selector: str = 'default') -> Dict:
+ """Add domain to KeyTable and SigningTable."""
+ try:
+ key_path = os.path.join(cls.OPENDKIM_KEYS_DIR, domain, f'{selector}.private')
+
+ # Add to KeyTable
+ key_entry = f'{selector}._domainkey.{domain} {domain}:{selector}:{key_path}\n'
+ result = run_privileged(['cat', cls.KEY_TABLE])
+ if domain not in (result.stdout or ''):
+ run_privileged(['tee', '-a', cls.KEY_TABLE], input=key_entry)
+
+ # Add to SigningTable
+ signing_entry = f'*@{domain} {selector}._domainkey.{domain}\n'
+ result = run_privileged(['cat', cls.SIGNING_TABLE])
+ if domain not in (result.stdout or ''):
+ run_privileged(['tee', '-a', cls.SIGNING_TABLE], input=signing_entry)
+
+ # Add to TrustedHosts
+ result = run_privileged(['cat', cls.TRUSTED_HOSTS])
+ if domain not in (result.stdout or ''):
+ run_privileged(['tee', '-a', cls.TRUSTED_HOSTS], input=f'*.{domain}\n')
+
+ # Reload OpenDKIM
+ ServiceControl.restart('opendkim', timeout=30)
+
+ return {'success': True, 'message': f'Domain {domain} added to DKIM'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def remove_domain(cls, domain: str) -> Dict:
+ """Remove domain from DKIM configuration."""
+ try:
+ # Remove from KeyTable
+ result = run_privileged(['cat', cls.KEY_TABLE])
+ lines = [l for l in (result.stdout or '').splitlines() if domain not in l]
+ run_privileged(['tee', cls.KEY_TABLE], input='\n'.join(lines) + '\n')
+
+ # Remove from SigningTable
+ result = run_privileged(['cat', cls.SIGNING_TABLE])
+ lines = [l for l in (result.stdout or '').splitlines() if domain not in l]
+ run_privileged(['tee', cls.SIGNING_TABLE], input='\n'.join(lines) + '\n')
+
+ # Remove from TrustedHosts
+ result = run_privileged(['cat', cls.TRUSTED_HOSTS])
+ lines = [l for l in (result.stdout or '').splitlines() if domain not in l]
+ run_privileged(['tee', cls.TRUSTED_HOSTS], input='\n'.join(lines) + '\n')
+
+ # Remove key files
+ key_dir = os.path.join(cls.OPENDKIM_KEYS_DIR, domain)
+ run_privileged(['rm', '-rf', key_dir])
+
+ ServiceControl.restart('opendkim', timeout=30)
+
+ return {'success': True, 'message': f'Domain {domain} removed from DKIM'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_dns_record(cls, domain: str, selector: str = 'default') -> Dict:
+ """Get the DKIM DNS TXT record content for a domain."""
+ try:
+ txt_file = os.path.join(cls.OPENDKIM_KEYS_DIR, domain, f'{selector}.txt')
+ result = run_privileged(['cat', txt_file])
+ if result.returncode != 0:
+ return {'success': False, 'error': 'DKIM key not found'}
+
+ record = result.stdout.strip()
+ key_match = re.search(r'p=([A-Za-z0-9+/=\s"]+)', record)
+ public_key = ''
+ if key_match:
+ public_key = key_match.group(1).replace(' ', '').replace('\n', '').replace('\t', '').replace('"', '')
+
+ return {
+ 'success': True,
+ 'dns_name': f'{selector}._domainkey.{domain}',
+ 'dns_value': f'v=DKIM1; k=rsa; p={public_key}',
+ 'raw_record': record,
+ }
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def verify_key(cls, domain: str, selector: str = 'default') -> Dict:
+ """Verify DKIM key configuration."""
+ try:
+ result = run_privileged([
+ 'opendkim-testkey',
+ '-d', domain,
+ '-s', selector,
+ '-vvv',
+ ])
+ success = result.returncode == 0
+ output = (result.stdout or '') + (result.stderr or '')
+ return {
+ 'success': success,
+ 'verified': success and 'key OK' in output,
+ 'output': output,
+ }
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def reload(cls) -> Dict:
+ """Reload OpenDKIM."""
+ try:
+ result = ServiceControl.restart('opendkim', timeout=30)
+ if result.returncode == 0:
+ return {'success': True, 'message': 'OpenDKIM restarted'}
+ return {'success': False, 'error': result.stderr or 'Restart failed'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
diff --git a/backend/app/plugins/serverkit-email/dovecot_service.py b/backend/app/plugins/serverkit-email/dovecot_service.py
new file mode 100644
index 00000000..55cf3d2f
--- /dev/null
+++ b/backend/app/plugins/serverkit-email/dovecot_service.py
@@ -0,0 +1,351 @@
+"""Dovecot IMAP/POP3 server management service."""
+import os
+import re
+import subprocess
+from typing import Dict, Optional
+
+from app.utils.system import PackageManager, ServiceControl, run_privileged
+from app import paths
+
+
+class DovecotService:
+ """Service for managing Dovecot (IMAP/POP3 server)."""
+
+ DOVECOT_CONF_DIR = '/etc/dovecot'
+ DOVECOT_CONF = '/etc/dovecot/dovecot.conf'
+ DOVECOT_AUTH_CONF = '/etc/dovecot/conf.d/10-auth.conf'
+ DOVECOT_MAIL_CONF = '/etc/dovecot/conf.d/10-mail.conf'
+ DOVECOT_MASTER_CONF = '/etc/dovecot/conf.d/10-master.conf'
+ DOVECOT_SSL_CONF = '/etc/dovecot/conf.d/10-ssl.conf'
+ DOVECOT_PASSWD_FILE = '/etc/dovecot/users'
+ AUTH_PASSWDFILE_CONF = '/etc/dovecot/conf.d/auth-passwdfile.conf.ext'
+
+ MAIL_CONF_CONTENT = """# Dovecot mail configuration - Managed by ServerKit
+mail_location = maildir:{vmail_dir}/%d/%n/Maildir
+namespace inbox {{
+ inbox = yes
+ separator = /
+}}
+mail_uid = {vmail_uid}
+mail_gid = {vmail_gid}
+mail_privileged_group = vmail
+first_valid_uid = {vmail_uid}
+last_valid_uid = {vmail_uid}
+"""
+
+ AUTH_CONF_CONTENT = """# Dovecot auth configuration - Managed by ServerKit
+disable_plaintext_auth = yes
+auth_mechanisms = plain login
+!include auth-passwdfile.conf.ext
+"""
+
+ AUTH_PASSWDFILE_CONTENT = """# Password file auth - Managed by ServerKit
+passdb {{
+ driver = passwd-file
+ args = scheme=SHA512-CRYPT /etc/dovecot/users
+}}
+userdb {{
+ driver = static
+ args = uid={vmail_uid} gid={vmail_gid} home={vmail_dir}/%d/%n
+}}
+"""
+
+ MASTER_CONF_CONTENT = """# Dovecot master configuration - Managed by ServerKit
+service imap-login {
+ inet_listener imap {
+ port = 0
+ }
+ inet_listener imaps {
+ port = 993
+ ssl = yes
+ }
+}
+service pop3-login {
+ inet_listener pop3 {
+ port = 0
+ }
+ inet_listener pop3s {
+ port = 995
+ ssl = yes
+ }
+}
+service lmtp {
+ unix_listener /var/spool/postfix/private/dovecot-lmtp {
+ mode = 0600
+ user = postfix
+ group = postfix
+ }
+}
+service auth {
+ unix_listener /var/spool/postfix/private/auth {
+ mode = 0666
+ user = postfix
+ group = postfix
+ }
+ unix_listener auth-userdb {
+ mode = 0600
+ user = vmail
+ group = vmail
+ }
+ user = dovecot
+}
+service auth-worker {
+ user = vmail
+}
+"""
+
+ SSL_CONF_CONTENT = """# Dovecot SSL configuration - Managed by ServerKit
+ssl = required
+ssl_cert = <{tls_cert}
+ssl_key = <{tls_key}
+ssl_min_protocol = TLSv1.2
+ssl_prefer_server_ciphers = yes
+"""
+
+ @classmethod
+ def get_status(cls) -> Dict:
+ """Get Dovecot installation and running status."""
+ installed = False
+ running = False
+ enabled = False
+ version = None
+ try:
+ result = subprocess.run(['which', 'dovecot'], capture_output=True, text=True)
+ installed = result.returncode == 0
+ if not installed:
+ installed = PackageManager.is_installed('dovecot-core') or PackageManager.is_installed('dovecot')
+ if installed:
+ running = ServiceControl.is_active('dovecot')
+ enabled = ServiceControl.is_enabled('dovecot')
+ result = subprocess.run(['dovecot', '--version'], capture_output=True, text=True)
+ version_match = re.search(r'(\d+\.\d+\.\d+)', result.stdout)
+ if version_match:
+ version = version_match.group(1)
+ except (subprocess.SubprocessError, FileNotFoundError):
+ pass
+
+ return {
+ 'installed': installed,
+ 'running': running,
+ 'enabled': enabled,
+ 'version': version,
+ }
+
+ @classmethod
+ def install(cls) -> Dict:
+ """Install Dovecot packages."""
+ try:
+ manager = PackageManager.detect()
+ if manager == 'apt':
+ packages = ['dovecot-core', 'dovecot-imapd', 'dovecot-pop3d', 'dovecot-lmtpd', 'dovecot-sieve']
+ else:
+ packages = ['dovecot']
+
+ result = PackageManager.install(packages, timeout=300)
+ if result.returncode != 0:
+ return {'success': False, 'error': result.stderr or 'Failed to install Dovecot'}
+
+ # Create empty passwd file
+ run_privileged(['touch', cls.DOVECOT_PASSWD_FILE])
+ run_privileged(['chown', 'vmail:dovecot', cls.DOVECOT_PASSWD_FILE])
+ run_privileged(['chmod', '640', cls.DOVECOT_PASSWD_FILE])
+
+ ServiceControl.enable('dovecot')
+
+ return {'success': True, 'message': 'Dovecot installed successfully'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def configure(cls, tls_cert: str = None, tls_key: str = None) -> Dict:
+ """Write Dovecot configuration files."""
+ try:
+ cert = tls_cert or '/etc/ssl/certs/ssl-cert-snakeoil.pem'
+ key = tls_key or '/etc/ssl/private/ssl-cert-snakeoil.key'
+
+ # 10-mail.conf
+ mail_conf = cls.MAIL_CONF_CONTENT.format(
+ vmail_dir=paths.VMAIL_DIR,
+ vmail_uid=paths.VMAIL_UID,
+ vmail_gid=paths.VMAIL_GID,
+ )
+ run_privileged(['tee', cls.DOVECOT_MAIL_CONF], input=mail_conf)
+
+ # 10-auth.conf
+ run_privileged(['tee', cls.DOVECOT_AUTH_CONF], input=cls.AUTH_CONF_CONTENT)
+
+ # auth-passwdfile.conf.ext
+ auth_passwd = cls.AUTH_PASSWDFILE_CONTENT.format(
+ vmail_uid=paths.VMAIL_UID,
+ vmail_gid=paths.VMAIL_GID,
+ vmail_dir=paths.VMAIL_DIR,
+ )
+ run_privileged(['tee', cls.AUTH_PASSWDFILE_CONF], input=auth_passwd)
+
+ # 10-master.conf
+ run_privileged(['tee', cls.DOVECOT_MASTER_CONF], input=cls.MASTER_CONF_CONTENT)
+
+ # 10-ssl.conf
+ ssl_conf = cls.SSL_CONF_CONTENT.format(tls_cert=cert, tls_key=key)
+ run_privileged(['tee', cls.DOVECOT_SSL_CONF], input=ssl_conf)
+
+ # Restart to apply
+ ServiceControl.restart('dovecot', timeout=30)
+
+ return {'success': True, 'message': 'Dovecot configured successfully'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def create_mailbox(cls, email: str, password: str, domain: str, username: str, quota_mb: int = 1024) -> Dict:
+ """Create a virtual mailbox with password entry."""
+ try:
+ # Generate password hash using doveadm
+ result = run_privileged(['doveadm', 'pw', '-s', 'SHA512-CRYPT', '-p', password])
+ if result.returncode != 0:
+ return {'success': False, 'error': 'Failed to hash password'}
+
+ password_hash = result.stdout.strip()
+
+ # Build passwd-file entry
+ # Format: user@domain:{scheme}hash:uid:gid:home::userdb_quota_rule=*:storage=NM
+ entry = f'{email}:{password_hash}:{paths.VMAIL_UID}:{paths.VMAIL_GID}:{paths.VMAIL_DIR}/{domain}/{username}::userdb_quota_rule=*:storage={quota_mb}M'
+
+ # Append to passwd file
+ run_privileged(['tee', '-a', cls.DOVECOT_PASSWD_FILE], input=entry + '\n')
+
+ # Create Maildir
+ maildir = os.path.join(paths.VMAIL_DIR, domain, username, 'Maildir')
+ run_privileged(['mkdir', '-p', f'{maildir}/cur', f'{maildir}/new', f'{maildir}/tmp'])
+ run_privileged(['chown', '-R', f'{paths.VMAIL_UID}:{paths.VMAIL_GID}',
+ os.path.join(paths.VMAIL_DIR, domain, username)])
+
+ return {'success': True, 'message': f'Mailbox {email} created'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def delete_mailbox(cls, email: str, domain: str, username: str, remove_files: bool = False) -> Dict:
+ """Delete a virtual mailbox."""
+ try:
+ # Remove from passwd file
+ result = run_privileged(['cat', cls.DOVECOT_PASSWD_FILE])
+ lines = (result.stdout or '').splitlines()
+ new_lines = [l for l in lines if not l.startswith(f'{email}:')]
+ run_privileged(['tee', cls.DOVECOT_PASSWD_FILE], input='\n'.join(new_lines) + '\n')
+
+ # Optionally remove Maildir
+ if remove_files:
+ mailbox_path = os.path.join(paths.VMAIL_DIR, domain, username)
+ run_privileged(['rm', '-rf', mailbox_path])
+
+ return {'success': True, 'message': f'Mailbox {email} deleted'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def change_password(cls, email: str, new_password: str) -> Dict:
+ """Change a mailbox password."""
+ try:
+ # Generate new hash
+ result = run_privileged(['doveadm', 'pw', '-s', 'SHA512-CRYPT', '-p', new_password])
+ if result.returncode != 0:
+ return {'success': False, 'error': 'Failed to hash password'}
+
+ new_hash = result.stdout.strip()
+
+ # Read current file
+ result = run_privileged(['cat', cls.DOVECOT_PASSWD_FILE])
+ lines = (result.stdout or '').splitlines()
+
+ updated = False
+ new_lines = []
+ for line in lines:
+ if line.startswith(f'{email}:'):
+ parts = line.split(':')
+ parts[1] = new_hash
+ new_lines.append(':'.join(parts))
+ updated = True
+ else:
+ new_lines.append(line)
+
+ if not updated:
+ return {'success': False, 'error': f'Account {email} not found'}
+
+ run_privileged(['tee', cls.DOVECOT_PASSWD_FILE], input='\n'.join(new_lines) + '\n')
+
+ return {'success': True, 'message': 'Password changed'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def set_quota(cls, email: str, quota_mb: int) -> Dict:
+ """Update mailbox quota."""
+ try:
+ result = run_privileged(['cat', cls.DOVECOT_PASSWD_FILE])
+ lines = (result.stdout or '').splitlines()
+
+ updated = False
+ new_lines = []
+ for line in lines:
+ if line.startswith(f'{email}:'):
+ # Replace quota in the userdb_quota_rule field
+ line = re.sub(r'userdb_quota_rule=\*:storage=\d+M',
+ f'userdb_quota_rule=*:storage={quota_mb}M', line)
+ new_lines.append(line)
+ updated = True
+ else:
+ new_lines.append(line)
+
+ if not updated:
+ return {'success': False, 'error': f'Account {email} not found'}
+
+ run_privileged(['tee', cls.DOVECOT_PASSWD_FILE], input='\n'.join(new_lines) + '\n')
+
+ return {'success': True, 'message': f'Quota set to {quota_mb}MB'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_quota_usage(cls, email: str) -> Dict:
+ """Get mailbox quota usage."""
+ try:
+ result = run_privileged(['doveadm', 'quota', 'get', '-u', email])
+ if result.returncode != 0:
+ return {'success': False, 'error': 'Failed to get quota'}
+
+ # Parse output
+ usage = {'storage_used': 0, 'storage_limit': 0, 'message_count': 0}
+ for line in result.stdout.splitlines():
+ parts = line.split()
+ if len(parts) >= 4 and parts[0] == 'STORAGE':
+ usage['storage_used'] = int(parts[1]) // 1024 # KB to MB
+ usage['storage_limit'] = int(parts[2]) // 1024 if parts[2] != '-' else 0
+ elif len(parts) >= 4 and parts[0] == 'MESSAGE':
+ usage['message_count'] = int(parts[1])
+
+ return {'success': True, **usage}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def reload(cls) -> Dict:
+ """Reload Dovecot configuration."""
+ try:
+ result = ServiceControl.reload('dovecot', timeout=30)
+ if result.returncode == 0:
+ return {'success': True, 'message': 'Dovecot reloaded'}
+ return {'success': False, 'error': result.stderr or 'Reload failed'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def restart(cls) -> Dict:
+ """Restart Dovecot."""
+ try:
+ result = ServiceControl.restart('dovecot', timeout=30)
+ if result.returncode == 0:
+ return {'success': True, 'message': 'Dovecot restarted'}
+ return {'success': False, 'error': result.stderr or 'Restart failed'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
diff --git a/backend/app/plugins/serverkit-email/email.py b/backend/app/plugins/serverkit-email/email.py
new file mode 100644
index 00000000..45afdf28
--- /dev/null
+++ b/backend/app/plugins/serverkit-email/email.py
@@ -0,0 +1,426 @@
+"""Email Server API endpoints for managing mail services, domains, accounts, and DNS.
+
+Lives in the serverkit-email extension (app.plugins.serverkit-email.email after
+install). Intra-extension modules are imported relatively; core services
+(postfix relay, DNS, relay-config, RBAC) are imported absolutely — the mail
+server extends the core, never the other way around.
+"""
+from flask import Blueprint, request, jsonify
+
+from app.middleware.rbac import admin_required, viewer_required
+from app.services.dns_provider_service import DNSProviderService
+from app.services.postfix_service import PostfixService
+from app.services.email_relay_service import EmailRelayService
+from .email_service import EmailService
+from .spamassassin_service import SpamAssassinService
+from .roundcube_service import RoundcubeService
+
+email_bp = Blueprint('email', __name__)
+
+
+# ── Status & Installation ──
+
+@email_bp.route('/status', methods=['GET'])
+@viewer_required
+def get_status():
+ """Get aggregate email server status."""
+ roundcube = RoundcubeService.get_status()
+ status = EmailService.get_status()
+ status['roundcube'] = roundcube
+ return jsonify(status), 200
+
+
+@email_bp.route('/install', methods=['POST'])
+@admin_required
+def install():
+ """Install and configure all email components."""
+ data = request.get_json() or {}
+ hostname = data.get('hostname')
+ result = EmailService.install_all(hostname)
+ return jsonify(result), 200 if result.get('success') else 500
+
+
+@email_bp.route('/service/<component>/<action>', methods=['POST'])
+@admin_required
+def control_service(component, action):
+ """Start/stop/restart an email component."""
+ result = EmailService.control_service(component, action)
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+# ── Domains ──
+
+@email_bp.route('/domains', methods=['GET'])
+@viewer_required
+def list_domains():
+ """List all email domains."""
+ domains = EmailService.get_domains()
+ return jsonify({'domains': domains}), 200
+
+
+@email_bp.route('/domains', methods=['POST'])
+@admin_required
+def add_domain():
+ """Add an email domain."""
+ data = request.get_json()
+ if not data or not data.get('name'):
+ return jsonify({'success': False, 'error': 'Domain name is required'}), 400
+ result = EmailService.add_domain(
+ data['name'],
+ dns_provider_id=data.get('dns_provider_id'),
+ dns_zone_id=data.get('dns_zone_id'),
+ )
+ return jsonify(result), 201 if result.get('success') else 400
+
+
+@email_bp.route('/domains/<int:domain_id>', methods=['GET'])
+@viewer_required
+def get_domain(domain_id):
+ """Get domain details."""
+ result = EmailService.get_domain(domain_id)
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 404
+
+
+@email_bp.route('/domains/<int:domain_id>', methods=['DELETE'])
+@admin_required
+def remove_domain(domain_id):
+ """Remove an email domain."""
+ result = EmailService.remove_domain(domain_id)
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+@email_bp.route('/domains/<int:domain_id>/verify-dns', methods=['POST'])
+@viewer_required
+def verify_dns(domain_id):
+ """Verify DNS records for a domain."""
+ result = EmailService.verify_dns(domain_id)
+ return jsonify(result), 200
+
+
+@email_bp.route('/domains/<int:domain_id>/deploy-dns', methods=['POST'])
+@admin_required
+def deploy_dns(domain_id):
+ """Deploy DNS records via provider API."""
+ from app.models.email import EmailDomain
+ domain = EmailDomain.query.get(domain_id)
+ if not domain:
+ return jsonify({'success': False, 'error': 'Domain not found'}), 404
+ if not domain.dns_provider_id or not domain.dns_zone_id:
+ return jsonify({'success': False, 'error': 'No DNS provider configured for this domain'}), 400
+ result = DNSProviderService.deploy_email_records(
+ domain.dns_provider_id,
+ domain.dns_zone_id,
+ domain.name,
+ domain.dkim_selector or 'default',
+ domain.dkim_public_key or '',
+ )
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+# ── Accounts ──
+
+@email_bp.route('/domains/<int:domain_id>/accounts', methods=['GET'])
+@viewer_required
+def list_accounts(domain_id):
+ """List email accounts for a domain."""
+ accounts = EmailService.get_accounts(domain_id)
+ return jsonify({'accounts': accounts}), 200
+
+
+@email_bp.route('/domains/<int:domain_id>/accounts', methods=['POST'])
+@admin_required
+def create_account(domain_id):
+ """Create an email account."""
+ data = request.get_json()
+ if not data:
+ return jsonify({'success': False, 'error': 'Request body required'}), 400
+ username = data.get('username')
+ password = data.get('password')
+ if not username or not password:
+ return jsonify({'success': False, 'error': 'Username and password are required'}), 400
+ result = EmailService.add_account(
+ domain_id,
+ username,
+ password,
+ quota_mb=data.get('quota_mb', 1024),
+ )
+ return jsonify(result), 201 if result.get('success') else 400
+
+
+@email_bp.route('/accounts/<int:account_id>', methods=['GET'])
+@viewer_required
+def get_account(account_id):
+ """Get account details."""
+ from app.models.email import EmailAccount
+ account = EmailAccount.query.get(account_id)
+ if not account:
+ return jsonify({'success': False, 'error': 'Account not found'}), 404
+ return jsonify({'success': True, 'account': account.to_dict()}), 200
+
+
+@email_bp.route('/accounts/<int:account_id>', methods=['PUT'])
+@admin_required
+def update_account(account_id):
+ """Update account settings."""
+ data = request.get_json() or {}
+ result = EmailService.update_account(
+ account_id,
+ quota_mb=data.get('quota_mb'),
+ is_active=data.get('is_active'),
+ )
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+@email_bp.route('/accounts/<int:account_id>', methods=['DELETE'])
+@admin_required
+def delete_account(account_id):
+ """Delete an email account."""
+ result = EmailService.delete_account(account_id)
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+@email_bp.route('/accounts/<int:account_id>/password', methods=['POST'])
+@admin_required
+def change_password(account_id):
+ """Change account password."""
+ data = request.get_json()
+ if not data or not data.get('password'):
+ return jsonify({'success': False, 'error': 'New password is required'}), 400
+ result = EmailService.change_password(account_id, data['password'])
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+# ── Aliases ──
+
+@email_bp.route('/domains/<int:domain_id>/aliases', methods=['GET'])
+@viewer_required
+def list_aliases(domain_id):
+ """List email aliases for a domain."""
+ aliases = EmailService.get_aliases(domain_id)
+ return jsonify({'aliases': aliases}), 200
+
+
+@email_bp.route('/domains/<int:domain_id>/aliases', methods=['POST'])
+@admin_required
+def create_alias(domain_id):
+ """Create an email alias."""
+ data = request.get_json()
+ if not data or not data.get('source') or not data.get('destination'):
+ return jsonify({'success': False, 'error': 'Source and destination are required'}), 400
+ result = EmailService.add_alias(domain_id, data['source'], data['destination'])
+ return jsonify(result), 201 if result.get('success') else 400
+
+
+@email_bp.route('/aliases/<int:alias_id>', methods=['DELETE'])
+@admin_required
+def delete_alias(alias_id):
+ """Delete an email alias."""
+ result = EmailService.remove_alias(alias_id)
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+# ── Forwarding Rules ──
+
+@email_bp.route('/accounts/<int:account_id>/forwarding', methods=['GET'])
+@viewer_required
+def list_forwarding(account_id):
+ """List forwarding rules for an account."""
+ rules = EmailService.get_forwarding(account_id)
+ return jsonify({'rules': rules}), 200
+
+
+@email_bp.route('/accounts/<int:account_id>/forwarding', methods=['POST'])
+@admin_required
+def create_forwarding(account_id):
+ """Create a forwarding rule."""
+ data = request.get_json()
+ if not data or not data.get('destination'):
+ return jsonify({'success': False, 'error': 'Destination is required'}), 400
+ result = EmailService.add_forwarding(
+ account_id,
+ data['destination'],
+ keep_copy=data.get('keep_copy', True),
+ )
+ return jsonify(result), 201 if result.get('success') else 400
+
+
+@email_bp.route('/forwarding/<int:rule_id>', methods=['PUT'])
+@admin_required
+def update_forwarding(rule_id):
+ """Update a forwarding rule."""
+ data = request.get_json() or {}
+ result = EmailService.update_forwarding(
+ rule_id,
+ destination=data.get('destination'),
+ keep_copy=data.get('keep_copy'),
+ is_active=data.get('is_active'),
+ )
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+@email_bp.route('/forwarding/<int:rule_id>', methods=['DELETE'])
+@admin_required
+def delete_forwarding(rule_id):
+ """Delete a forwarding rule."""
+ result = EmailService.remove_forwarding(rule_id)
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+# ── DNS Providers ──
+# Moved to core (app/api/dns_providers.py, same /api/v1/email/dns-providers
+# paths): the Connections page and wildcard TLS need them without this
+# extension installed.
+
+
+# ── Outbound SMTP Relay (smarthost) ──
+
+@email_bp.route('/relay', methods=['GET'])
+@viewer_required
+def get_relay():
+ """Get the outbound SMTP relay configuration (password masked)."""
+ return jsonify(EmailRelayService.get_config()), 200
+
+
+@email_bp.route('/relay', methods=['PUT'])
+@admin_required
+def save_relay():
+ """Save the relay configuration and apply it to Postfix (if installed)."""
+ data = request.get_json() or {}
+ if not data.get('host'):
+ return jsonify({'success': False, 'error': 'A relay host is required'}), 400
+ result = EmailRelayService.save_config(data)
+ return jsonify(result), 200
+
+
+@email_bp.route('/relay/test', methods=['POST'])
+@admin_required
+def test_relay():
+ """Open a real SMTP connection to validate the relay credentials."""
+ data = request.get_json() or {}
+ result = EmailRelayService.test(data)
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+@email_bp.route('/relay', methods=['DELETE'])
+@admin_required
+def disable_relay():
+ """Disable the outbound relay (revert Postfix to direct delivery)."""
+ result = EmailRelayService.disable()
+ return jsonify(result), 200
+
+
+# ── SpamAssassin Config ──
+
+@email_bp.route('/spam/config', methods=['GET'])
+@viewer_required
+def get_spam_config():
+ """Get SpamAssassin configuration."""
+ result = SpamAssassinService.get_config()
+ return jsonify(result), 200
+
+
+@email_bp.route('/spam/config', methods=['PUT'])
+@admin_required
+def update_spam_config():
+ """Update SpamAssassin configuration."""
+ data = request.get_json()
+ if not data:
+ return jsonify({'success': False, 'error': 'Request body required'}), 400
+ result = SpamAssassinService.configure(data)
+ if result.get('success'):
+ SpamAssassinService.reload()
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+@email_bp.route('/spam/update-rules', methods=['POST'])
+@admin_required
+def update_spam_rules():
+ """Update SpamAssassin rules."""
+ result = SpamAssassinService.update_rules()
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+# ── Roundcube Webmail ──
+
+@email_bp.route('/webmail/status', methods=['GET'])
+@viewer_required
+def webmail_status():
+ """Get Roundcube webmail status."""
+ result = RoundcubeService.get_status()
+ return jsonify(result), 200
+
+
+@email_bp.route('/webmail/install', methods=['POST'])
+@admin_required
+def webmail_install():
+ """Install Roundcube webmail."""
+ data = request.get_json() or {}
+ result = RoundcubeService.install(
+ imap_host=data.get('imap_host', 'host.docker.internal'),
+ smtp_host=data.get('smtp_host', 'host.docker.internal'),
+ domain=(data.get('domain') or '').strip() or None,
+ )
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+@email_bp.route('/webmail/service/<action>', methods=['POST'])
+@admin_required
+def webmail_control(action):
+ """Start/stop/restart Roundcube."""
+ actions = {
+ 'start': RoundcubeService.start,
+ 'stop': RoundcubeService.stop,
+ 'restart': RoundcubeService.restart,
+ }
+ if action not in actions:
+ return jsonify({'success': False, 'error': 'Invalid action'}), 400
+ result = actions[action]()
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+@email_bp.route('/webmail/configure-proxy', methods=['POST'])
+@admin_required
+def webmail_configure_proxy():
+ """Configure Nginx reverse proxy for Roundcube."""
+ data = request.get_json()
+ if not data or not data.get('domain'):
+ return jsonify({'success': False, 'error': 'Domain is required'}), 400
+ result = RoundcubeService.configure_nginx_proxy(data['domain'])
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+# ── Mail Queue & Logs ──
+
+@email_bp.route('/queue', methods=['GET'])
+@viewer_required
+def get_queue():
+ """Get Postfix mail queue."""
+ result = PostfixService.get_queue()
+ return jsonify(result), 200
+
+
+@email_bp.route('/queue/flush', methods=['POST'])
+@admin_required
+def flush_queue():
+ """Flush the mail queue."""
+ result = PostfixService.flush_queue()
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+@email_bp.route('/queue/<queue_id>', methods=['DELETE'])
+@admin_required
+def delete_queue_item(queue_id):
+ """Delete a message from the queue."""
+ result = PostfixService.delete_from_queue(queue_id)
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+@email_bp.route('/logs', methods=['GET'])
+@viewer_required
+def get_logs():
+ """Get mail logs."""
+ lines = request.args.get('lines', 100, type=int)
+ result = PostfixService.get_logs(lines)
+ return jsonify(result), 200
diff --git a/backend/app/plugins/serverkit-email/email_service.py b/backend/app/plugins/serverkit-email/email_service.py
new file mode 100644
index 00000000..de2333c1
--- /dev/null
+++ b/backend/app/plugins/serverkit-email/email_service.py
@@ -0,0 +1,546 @@
+"""Email service orchestrator — delegates to sub-services for each component."""
+import logging
+import subprocess
+from typing import Dict, List, Optional
+
+from app import db
+from app.models.email import EmailDomain, EmailAccount, EmailAlias, EmailForwardingRule
+from app.services.postfix_service import PostfixService
+from app.utils.system import PackageManager, ServiceControl
+from .dovecot_service import DovecotService
+from .dkim_service import DKIMService
+from .spamassassin_service import SpamAssassinService
+from .roundcube_service import RoundcubeService
+
+logger = logging.getLogger(__name__)
+
+
+class EmailService:
+ """High-level email service that coordinates Postfix, Dovecot, DKIM, and SpamAssassin."""
+
+ COMPONENTS = {
+ 'postfix': PostfixService,
+ 'dovecot': DovecotService,
+ 'opendkim': DKIMService,
+ 'spamassassin': SpamAssassinService,
+ }
+
+ # ── Status ──
+
+ @classmethod
+ def get_status(cls) -> Dict:
+ """Get aggregate email server status."""
+ postfix = PostfixService.get_status()
+ dovecot = DovecotService.get_status()
+ dkim = DKIMService.get_status()
+ spam = SpamAssassinService.get_status()
+
+ all_installed = postfix['installed'] and dovecot['installed']
+ all_running = postfix.get('running', False) and dovecot.get('running', False)
+
+ return {
+ 'installed': all_installed,
+ 'running': all_running,
+ 'postfix': postfix,
+ 'dovecot': dovecot,
+ 'dkim': dkim,
+ 'spamassassin': spam,
+ }
+
+ # ── Installation ──
+
+ @classmethod
+ def install_all(cls, hostname: str = None) -> Dict:
+ """Install and configure all email components."""
+ results = {}
+
+ # 1. Install Postfix
+ results['postfix'] = PostfixService.install(hostname=hostname)
+ if not results['postfix'].get('success'):
+ return {'success': False, 'error': 'Postfix installation failed', 'results': results}
+
+ # 2. Configure Postfix
+ postfix_config = PostfixService.configure(hostname=hostname)
+ if not postfix_config.get('success'):
+ logger.warning(f"Postfix configuration warning: {postfix_config.get('error')}")
+
+ # 3. Install Dovecot
+ results['dovecot'] = DovecotService.install()
+ if not results['dovecot'].get('success'):
+ return {'success': False, 'error': 'Dovecot installation failed', 'results': results}
+
+ # 4. Configure Dovecot
+ dovecot_config = DovecotService.configure()
+ if not dovecot_config.get('success'):
+ logger.warning(f"Dovecot configuration warning: {dovecot_config.get('error')}")
+
+ # 5. Install OpenDKIM
+ results['dkim'] = DKIMService.install()
+ if not results['dkim'].get('success'):
+ logger.warning(f"DKIM installation warning: {results['dkim'].get('error')}")
+
+ # 6. Install SpamAssassin
+ results['spamassassin'] = SpamAssassinService.install()
+ if not results['spamassassin'].get('success'):
+ logger.warning(f"SpamAssassin installation warning: {results['spamassassin'].get('error')}")
+
+ all_ok = all(r.get('success') for r in results.values())
+ return {
+ 'success': all_ok,
+ 'message': 'All email components installed' if all_ok else 'Some components had issues',
+ 'results': results,
+ }
+
+ # ── Service Control ──
+
+ @classmethod
+ def control_service(cls, component: str, action: str) -> Dict:
+ """Start/stop/restart an email component."""
+ if component not in cls.COMPONENTS and component != 'roundcube':
+ return {'success': False, 'error': f'Unknown component: {component}'}
+
+ if action not in ('start', 'stop', 'restart', 'reload'):
+ return {'success': False, 'error': f'Invalid action: {action}'}
+
+ try:
+ if component == 'roundcube':
+ actions = {
+ 'start': RoundcubeService.start,
+ 'stop': RoundcubeService.stop,
+ 'restart': RoundcubeService.restart,
+ 'reload': RoundcubeService.restart,
+ }
+ return actions[action]()
+
+ service_name = component
+ if action == 'start':
+ result = ServiceControl.start(service_name, timeout=30)
+ elif action == 'stop':
+ result = ServiceControl.stop(service_name, timeout=30)
+ elif action == 'restart':
+ result = ServiceControl.restart(service_name, timeout=30)
+ elif action == 'reload':
+ result = ServiceControl.reload(service_name, timeout=30)
+
+ if result.returncode == 0:
+ return {'success': True, 'message': f'{component} {action} successful'}
+ return {'success': False, 'error': result.stderr or f'{action} failed'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ # ── Domains ──
+
+ @classmethod
+ def get_domains(cls) -> List[Dict]:
+ """List all email domains."""
+ domains = EmailDomain.query.all()
+ return [d.to_dict() for d in domains]
+
+ @classmethod
+ def add_domain(cls, name: str, dns_provider_id: int = None, dns_zone_id: str = None) -> Dict:
+ """Add an email domain."""
+ try:
+ existing = EmailDomain.query.filter_by(name=name).first()
+ if existing:
+ return {'success': False, 'error': f'Domain {name} already exists'}
+
+ domain = EmailDomain(
+ name=name,
+ dns_provider_id=dns_provider_id,
+ dns_zone_id=dns_zone_id,
+ )
+ db.session.add(domain)
+ db.session.commit()
+
+ # Add to Postfix virtual domains
+ PostfixService.add_domain(name)
+
+ # Generate DKIM key
+ dkim_result = DKIMService.generate_key(name)
+ if dkim_result.get('success'):
+ domain.dkim_selector = 'default'
+ domain.dkim_private_key_path = dkim_result.get('private_key_path')
+ domain.dkim_public_key = dkim_result.get('public_key')
+ domain.spf_record = f'v=spf1 mx a ~all'
+ domain.dmarc_record = f'v=DMARC1; p=quarantine; rua=mailto:dmarc@{name}; pct=100'
+ DKIMService.add_domain(name)
+ db.session.commit()
+
+ return {'success': True, 'domain': domain.to_dict(), 'message': f'Domain {name} added'}
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_domain(cls, domain_id: int) -> Dict:
+ """Get domain details."""
+ domain = EmailDomain.query.get(domain_id)
+ if not domain:
+ return {'success': False, 'error': 'Domain not found'}
+ return {'success': True, 'domain': domain.to_dict()}
+
+ @classmethod
+ def remove_domain(cls, domain_id: int) -> Dict:
+ """Remove an email domain and all its accounts/aliases."""
+ try:
+ domain = EmailDomain.query.get(domain_id)
+ if not domain:
+ return {'success': False, 'error': 'Domain not found'}
+
+ domain_name = domain.name
+
+ # Remove accounts from Dovecot/Postfix
+ for account in domain.accounts:
+ DovecotService.delete_mailbox(account.email, domain_name, account.username, remove_files=True)
+ PostfixService.remove_mailbox(account.email)
+
+ # Remove aliases from Postfix
+ for alias in domain.aliases:
+ PostfixService.remove_alias(alias.source)
+
+ # Remove from DKIM
+ DKIMService.remove_domain(domain_name)
+
+ # Remove from Postfix virtual domains
+ PostfixService.remove_domain(domain_name)
+
+ # Delete from database
+ db.session.delete(domain)
+ db.session.commit()
+
+ return {'success': True, 'message': f'Domain {domain_name} removed'}
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def verify_dns(cls, domain_id: int) -> Dict:
+ """Verify DNS records for a domain."""
+ domain = EmailDomain.query.get(domain_id)
+ if not domain:
+ return {'success': False, 'error': 'Domain not found'}
+
+ results = {}
+ name = domain.name
+
+ # Check MX record
+ try:
+ result = subprocess.run(['dig', '+short', 'MX', name], capture_output=True, text=True, timeout=10)
+ results['mx'] = {
+ 'found': bool(result.stdout.strip()),
+ 'value': result.stdout.strip() or None,
+ }
+ except Exception:
+ results['mx'] = {'found': False, 'error': 'DNS lookup failed'}
+
+ # Check SPF record
+ try:
+ result = subprocess.run(['dig', '+short', 'TXT', name], capture_output=True, text=True, timeout=10)
+ spf_found = 'v=spf1' in (result.stdout or '')
+ results['spf'] = {
+ 'found': spf_found,
+ 'value': result.stdout.strip() or None,
+ }
+ except Exception:
+ results['spf'] = {'found': False, 'error': 'DNS lookup failed'}
+
+ # Check DKIM record
+ selector = domain.dkim_selector or 'default'
+ try:
+ dkim_name = f'{selector}._domainkey.{name}'
+ result = subprocess.run(['dig', '+short', 'TXT', dkim_name], capture_output=True, text=True, timeout=10)
+ dkim_found = 'v=DKIM1' in (result.stdout or '')
+ results['dkim'] = {
+ 'found': dkim_found,
+ 'value': result.stdout.strip() or None,
+ 'name': dkim_name,
+ }
+ except Exception:
+ results['dkim'] = {'found': False, 'error': 'DNS lookup failed'}
+
+ # Check DMARC record
+ try:
+ dmarc_name = f'_dmarc.{name}'
+ result = subprocess.run(['dig', '+short', 'TXT', dmarc_name], capture_output=True, text=True, timeout=10)
+ dmarc_found = 'v=DMARC1' in (result.stdout or '')
+ results['dmarc'] = {
+ 'found': dmarc_found,
+ 'value': result.stdout.strip() or None,
+ }
+ except Exception:
+ results['dmarc'] = {'found': False, 'error': 'DNS lookup failed'}
+
+ all_ok = all(r.get('found') for r in results.values())
+ return {
+ 'success': True,
+ 'domain': name,
+ 'all_verified': all_ok,
+ 'records': results,
+ }
+
+ # ── Accounts ──
+
+ @classmethod
+ def get_accounts(cls, domain_id: int) -> List[Dict]:
+ """List email accounts for a domain."""
+ accounts = EmailAccount.query.filter_by(domain_id=domain_id).all()
+ return [a.to_dict() for a in accounts]
+
+ @classmethod
+ def add_account(cls, domain_id: int, username: str, password: str, quota_mb: int = 1024) -> Dict:
+ """Create an email account."""
+ try:
+ domain = EmailDomain.query.get(domain_id)
+ if not domain:
+ return {'success': False, 'error': 'Domain not found'}
+
+ email = f'{username}@{domain.name}'
+
+ existing = EmailAccount.query.filter_by(email=email).first()
+ if existing:
+ return {'success': False, 'error': f'Account {email} already exists'}
+
+ # Create mailbox in Dovecot
+ dovecot_result = DovecotService.create_mailbox(email, password, domain.name, username, quota_mb)
+ if not dovecot_result.get('success'):
+ return dovecot_result
+
+ # Add to Postfix virtual mailboxes
+ PostfixService.add_mailbox(email, domain.name, username)
+
+ # Get password hash for storage
+ password_hash = dovecot_result.get('password_hash', 'stored_in_dovecot')
+
+ account = EmailAccount(
+ email=email,
+ username=username,
+ password_hash=password_hash,
+ domain_id=domain_id,
+ quota_mb=quota_mb,
+ )
+ db.session.add(account)
+ db.session.commit()
+
+ return {'success': True, 'account': account.to_dict(), 'message': f'Account {email} created'}
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def update_account(cls, account_id: int, quota_mb: int = None, is_active: bool = None) -> Dict:
+ """Update account settings."""
+ try:
+ account = EmailAccount.query.get(account_id)
+ if not account:
+ return {'success': False, 'error': 'Account not found'}
+
+ if quota_mb is not None:
+ account.quota_mb = quota_mb
+ DovecotService.set_quota(account.email, quota_mb)
+
+ if is_active is not None:
+ account.is_active = is_active
+
+ db.session.commit()
+ return {'success': True, 'account': account.to_dict(), 'message': 'Account updated'}
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def delete_account(cls, account_id: int) -> Dict:
+ """Delete an email account."""
+ try:
+ account = EmailAccount.query.get(account_id)
+ if not account:
+ return {'success': False, 'error': 'Account not found'}
+
+ email = account.email
+ domain_name = account.domain.name if account.domain else ''
+ username = account.username
+
+ # Remove from Dovecot
+ DovecotService.delete_mailbox(email, domain_name, username, remove_files=True)
+
+ # Remove from Postfix
+ PostfixService.remove_mailbox(email)
+
+ db.session.delete(account)
+ db.session.commit()
+
+ return {'success': True, 'message': f'Account {email} deleted'}
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def change_password(cls, account_id: int, new_password: str) -> Dict:
+ """Change an account password."""
+ try:
+ account = EmailAccount.query.get(account_id)
+ if not account:
+ return {'success': False, 'error': 'Account not found'}
+
+ result = DovecotService.change_password(account.email, new_password)
+ if not result.get('success'):
+ return result
+
+ account.password_hash = 'updated_in_dovecot'
+ db.session.commit()
+
+ return {'success': True, 'message': 'Password changed successfully'}
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ # ── Aliases ──
+
+ @classmethod
+ def get_aliases(cls, domain_id: int) -> List[Dict]:
+ """List email aliases for a domain."""
+ aliases = EmailAlias.query.filter_by(domain_id=domain_id).all()
+ return [a.to_dict() for a in aliases]
+
+ @classmethod
+ def add_alias(cls, domain_id: int, source: str, destination: str) -> Dict:
+ """Create an email alias."""
+ try:
+ domain = EmailDomain.query.get(domain_id)
+ if not domain:
+ return {'success': False, 'error': 'Domain not found'}
+
+ # Add @ domain if not already qualified
+ if '@' not in source:
+ source = f'{source}@{domain.name}'
+
+ alias = EmailAlias(
+ source=source,
+ destination=destination,
+ domain_id=domain_id,
+ )
+ db.session.add(alias)
+ db.session.commit()
+
+ # Add to Postfix virtual aliases
+ PostfixService.add_alias(source, destination)
+
+ return {'success': True, 'alias': alias.to_dict(), 'message': f'Alias {source} created'}
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def remove_alias(cls, alias_id: int) -> Dict:
+ """Delete an email alias."""
+ try:
+ alias = EmailAlias.query.get(alias_id)
+ if not alias:
+ return {'success': False, 'error': 'Alias not found'}
+
+ PostfixService.remove_alias(alias.source)
+
+ db.session.delete(alias)
+ db.session.commit()
+
+ return {'success': True, 'message': 'Alias removed'}
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ # ── Forwarding Rules ──
+
+ @classmethod
+ def get_forwarding(cls, account_id: int) -> List[Dict]:
+ """List forwarding rules for an account."""
+ rules = EmailForwardingRule.query.filter_by(account_id=account_id).all()
+ return [r.to_dict() for r in rules]
+
+ @classmethod
+ def add_forwarding(cls, account_id: int, destination: str, keep_copy: bool = True) -> Dict:
+ """Create a forwarding rule."""
+ try:
+ account = EmailAccount.query.get(account_id)
+ if not account:
+ return {'success': False, 'error': 'Account not found'}
+
+ rule = EmailForwardingRule(
+ account_id=account_id,
+ destination=destination,
+ keep_copy=keep_copy,
+ )
+ db.session.add(rule)
+ db.session.commit()
+
+ # Update Postfix aliases for forwarding
+ cls._sync_forwarding_aliases(account)
+
+ return {'success': True, 'rule': rule.to_dict(), 'message': 'Forwarding rule created'}
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def update_forwarding(cls, rule_id: int, destination: str = None,
+ keep_copy: bool = None, is_active: bool = None) -> Dict:
+ """Update a forwarding rule."""
+ try:
+ rule = EmailForwardingRule.query.get(rule_id)
+ if not rule:
+ return {'success': False, 'error': 'Forwarding rule not found'}
+
+ if destination is not None:
+ rule.destination = destination
+ if keep_copy is not None:
+ rule.keep_copy = keep_copy
+ if is_active is not None:
+ rule.is_active = is_active
+
+ db.session.commit()
+
+ # Re-sync Postfix aliases
+ cls._sync_forwarding_aliases(rule.account)
+
+ return {'success': True, 'rule': rule.to_dict(), 'message': 'Forwarding rule updated'}
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def remove_forwarding(cls, rule_id: int) -> Dict:
+ """Delete a forwarding rule."""
+ try:
+ rule = EmailForwardingRule.query.get(rule_id)
+ if not rule:
+ return {'success': False, 'error': 'Forwarding rule not found'}
+
+ account = rule.account
+ db.session.delete(rule)
+ db.session.commit()
+
+ # Re-sync Postfix aliases
+ cls._sync_forwarding_aliases(account)
+
+ return {'success': True, 'message': 'Forwarding rule removed'}
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def _sync_forwarding_aliases(cls, account: EmailAccount):
+ """Sync forwarding rules to Postfix virtual aliases for an account."""
+ active_rules = [r for r in account.forwarding_rules if r.is_active]
+
+ if not active_rules:
+ # Remove any forwarding alias
+ PostfixService.remove_alias(account.email)
+ return
+
+ # Build destination list
+ destinations = [r.destination for r in active_rules]
+ # If any rule wants to keep a copy, include the original mailbox
+ if any(r.keep_copy for r in active_rules):
+ destinations.append(account.email)
+
+ # Remove old alias and add new one
+ PostfixService.remove_alias(account.email)
+ PostfixService.add_alias(account.email, ', '.join(destinations))
diff --git a/backend/app/plugins/serverkit-email/plugin.json b/backend/app/plugins/serverkit-email/plugin.json
new file mode 100644
index 00000000..cae41e3e
--- /dev/null
+++ b/backend/app/plugins/serverkit-email/plugin.json
@@ -0,0 +1,51 @@
+{
+ "name": "serverkit-email",
+ "display_name": "Email Server",
+ "version": "1.0.0",
+ "description": "Full mail-server stack with Postfix/Dovecot, domains, mailboxes, aliases, DKIM/SPF/DMARC, SpamAssassin filtering, and Roundcube webmail. Most panels never run a mail server, so it ships as an opt-in extension.",
+ "author": "ServerKit",
+ "license": "MIT",
+ "category": "integration",
+ "homepage": "https://github.com/jhd3197/ServerKit",
+ "permissions": [
+ "shell",
+ "filesystem",
+ "network"
+ ],
+ "min_panel_version": "1.7.0",
+ "entry_point": "email:email_bp",
+ "url_prefix": "/api/v1/email",
+ "icon": "<path d=\"M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z\"/><polyline points=\"22,6 12,13 2,6\"/>",
+ "contributions": {
+ "nav": [
+ {
+ "id": "email",
+ "label": "Email Server",
+ "route": "/email",
+ "category": "operations",
+ "icon": "<path d=\"M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z\"/><polyline points=\"22,6 12,13 2,6\"/>"
+ }
+ ],
+ "routes": [
+ {
+ "path": "email",
+ "component": "EmailPage"
+ },
+ {
+ "path": "email/:tab",
+ "component": "EmailPage"
+ }
+ ],
+ "page_titles": {
+ "/email": "Email Server"
+ },
+ "command_palette": [
+ {
+ "label": "Email",
+ "path": "/email",
+ "category": "Pages",
+ "keywords": "smtp postfix dovecot mail imap dkim webmail"
+ }
+ ]
+ }
+}
\ No newline at end of file
diff --git a/backend/app/plugins/serverkit-email/roundcube_service.py b/backend/app/plugins/serverkit-email/roundcube_service.py
new file mode 100644
index 00000000..85c93253
--- /dev/null
+++ b/backend/app/plugins/serverkit-email/roundcube_service.py
@@ -0,0 +1,213 @@
+"""Roundcube webmail management service (Docker-based)."""
+import subprocess
+from typing import Dict
+
+from app.utils.system import run_privileged, is_command_available
+
+
+class RoundcubeService:
+ """Service for managing Roundcube webmail via Docker."""
+
+ CONTAINER_NAME = 'serverkit-roundcube'
+ VOLUME_NAME = 'roundcube_data'
+ IMAGE = 'roundcube/roundcubemail:latest'
+ HOST_PORT = 9000
+
+ @classmethod
+ def get_status(cls) -> Dict:
+ """Get Roundcube container status."""
+ if not is_command_available('docker'):
+ return {'installed': False, 'running': False, 'error': 'Docker not available'}
+
+ try:
+ result = subprocess.run(
+ ['docker', 'inspect', '--format', '{{.State.Status}}', cls.CONTAINER_NAME],
+ capture_output=True, text=True,
+ )
+ if result.returncode != 0:
+ return {'installed': False, 'running': False}
+
+ status = result.stdout.strip()
+ return {
+ 'installed': True,
+ 'running': status == 'running',
+ 'status': status,
+ 'port': cls.HOST_PORT,
+ }
+ except Exception as e:
+ return {'installed': False, 'running': False, 'error': str(e)}
+
+ @classmethod
+ def install(cls, imap_host: str = 'host.docker.internal',
+ smtp_host: str = 'host.docker.internal',
+ domain: str = None) -> Dict:
+ """Install Roundcube via Docker container."""
+ if not is_command_available('docker'):
+ return {'success': False, 'error': 'Docker is not installed'}
+
+ try:
+ # Remove existing container if any
+ subprocess.run(
+ ['docker', 'rm', '-f', cls.CONTAINER_NAME],
+ capture_output=True, text=True,
+ )
+
+ # Create volume
+ subprocess.run(
+ ['docker', 'volume', 'create', cls.VOLUME_NAME],
+ capture_output=True, text=True,
+ )
+
+ # Run container
+ result = subprocess.run([
+ 'docker', 'run', '-d',
+ '--name', cls.CONTAINER_NAME,
+ '--restart', 'unless-stopped',
+ '--add-host', 'host.docker.internal:host-gateway',
+ '-p', f'{cls.HOST_PORT}:80',
+ '-e', f'ROUNDCUBEMAIL_DEFAULT_HOST=ssl://{imap_host}',
+ '-e', f'ROUNDCUBEMAIL_SMTP_SERVER=tls://{smtp_host}',
+ '-e', 'ROUNDCUBEMAIL_DEFAULT_PORT=993',
+ '-e', 'ROUNDCUBEMAIL_SMTP_PORT=587',
+ '-e', 'ROUNDCUBEMAIL_UPLOAD_MAX_FILESIZE=25M',
+ '-e', 'ROUNDCUBEMAIL_SKIN=elastic',
+ '-v', f'{cls.VOLUME_NAME}:/var/roundcube/db',
+ cls.IMAGE,
+ ], capture_output=True, text=True)
+
+ if result.returncode != 0:
+ return {'success': False, 'error': result.stderr or 'Failed to start container'}
+
+ # Build a public URL: prefer a supplied domain, then auto-generate
+ # webmail.<panel_domain>, and only fall back to localhost:port.
+ from app.services.site_domain_service import SiteDomainService
+ public_url = None
+ warning = None
+ if domain:
+ public_url = f'http://{domain}'
+ proxy_res = cls.configure_nginx_proxy(domain)
+ if not proxy_res.get('success'):
+ warning = proxy_res.get('error')
+ else:
+ panel_origin = SiteDomainService.panel_origin()
+ panel_host = None
+ if panel_origin:
+ from urllib.parse import urlparse
+ panel_host = urlparse(panel_origin).hostname
+ if panel_host:
+ webmail_domain = f'webmail.{panel_host}'
+ public_url = f'http://{webmail_domain}'
+ proxy_res = cls.configure_nginx_proxy(webmail_domain)
+ if not proxy_res.get('success'):
+ warning = proxy_res.get('error')
+
+ if not public_url:
+ public_url = f'http://localhost:{cls.HOST_PORT}'
+
+ result = {
+ 'success': True,
+ 'message': 'Roundcube installed successfully',
+ 'port': cls.HOST_PORT,
+ 'url': public_url,
+ }
+ if warning:
+ result['warning'] = warning
+ return result
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def uninstall(cls) -> Dict:
+ """Stop and remove Roundcube container."""
+ try:
+ subprocess.run(['docker', 'rm', '-f', cls.CONTAINER_NAME], capture_output=True, text=True)
+ return {'success': True, 'message': 'Roundcube uninstalled'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def start(cls) -> Dict:
+ """Start Roundcube container."""
+ try:
+ result = subprocess.run(
+ ['docker', 'start', cls.CONTAINER_NAME],
+ capture_output=True, text=True,
+ )
+ if result.returncode == 0:
+ return {'success': True, 'message': 'Roundcube started'}
+ return {'success': False, 'error': result.stderr or 'Start failed'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def stop(cls) -> Dict:
+ """Stop Roundcube container."""
+ try:
+ result = subprocess.run(
+ ['docker', 'stop', cls.CONTAINER_NAME],
+ capture_output=True, text=True,
+ )
+ if result.returncode == 0:
+ return {'success': True, 'message': 'Roundcube stopped'}
+ return {'success': False, 'error': result.stderr or 'Stop failed'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def restart(cls) -> Dict:
+ """Restart Roundcube container."""
+ try:
+ result = subprocess.run(
+ ['docker', 'restart', cls.CONTAINER_NAME],
+ capture_output=True, text=True,
+ )
+ if result.returncode == 0:
+ return {'success': True, 'message': 'Roundcube restarted'}
+ return {'success': False, 'error': result.stderr or 'Restart failed'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def configure_nginx_proxy(cls, domain: str) -> Dict:
+ """Create Nginx reverse proxy config for Roundcube."""
+ try:
+ from app.services.nginx_service import NginxService
+
+ config = f"""# Roundcube Webmail - Managed by ServerKit
+server {{
+ listen 80;
+ server_name {domain};
+
+ location / {{
+ proxy_pass http://127.0.0.1:{cls.HOST_PORT};
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ client_max_body_size 25m;
+ }}
+}}
+"""
+ site_name = f'roundcube-{domain.replace(".", "-")}'
+ config_path = f'/etc/nginx/sites-available/{site_name}'
+ enabled_path = f'/etc/nginx/sites-enabled/{site_name}'
+
+ run_privileged(['tee', config_path], input=config)
+ run_privileged(['ln', '-sf', config_path, enabled_path])
+
+ # Test and reload
+ test = run_privileged(['nginx', '-t'])
+ if test.returncode != 0:
+ # Rollback
+ run_privileged(['rm', '-f', enabled_path])
+ return {'success': False, 'error': f'Nginx config test failed: {test.stderr}'}
+
+ run_privileged(['systemctl', 'reload', 'nginx'])
+
+ return {
+ 'success': True,
+ 'message': f'Nginx proxy configured for {domain}',
+ 'url': f'http://{domain}',
+ }
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
diff --git a/backend/app/plugins/serverkit-email/spamassassin_service.py b/backend/app/plugins/serverkit-email/spamassassin_service.py
new file mode 100644
index 00000000..1418069d
--- /dev/null
+++ b/backend/app/plugins/serverkit-email/spamassassin_service.py
@@ -0,0 +1,253 @@
+"""SpamAssassin management service."""
+import os
+import re
+import subprocess
+from typing import Dict
+
+from app.utils.system import PackageManager, ServiceControl, run_privileged
+
+
+class SpamAssassinService:
+ """Service for managing SpamAssassin spam filtering."""
+
+ SPAMASSASSIN_CONF = '/etc/spamassassin/local.cf'
+ SPAMASSASSIN_DEFAULT = '/etc/default/spamassassin'
+ SPAMASS_MILTER_DEFAULT = '/etc/default/spamass-milter'
+
+ LOCAL_CF_TEMPLATE = """# SpamAssassin local configuration - Managed by ServerKit
+required_score {required_score}
+report_safe {report_safe}
+rewrite_header Subject {rewrite_subject}
+use_bayes {use_bayes}
+bayes_auto_learn {bayes_auto_learn}
+bayes_auto_learn_threshold_nonspam 0.1
+bayes_auto_learn_threshold_spam 12.0
+skip_rbl_checks {skip_rbl_checks}
+use_razor2 0
+use_pyzor 0
+
+# Network checks
+dns_available yes
+
+# Trusted networks
+trusted_networks 127.0.0.0/8
+internal_networks 127.0.0.0/8
+"""
+
+ DEFAULT_CONFIG = {
+ 'required_score': 5.0,
+ 'report_safe': 0,
+ 'rewrite_subject': '[SPAM]',
+ 'use_bayes': 1,
+ 'bayes_auto_learn': 1,
+ 'skip_rbl_checks': 0,
+ }
+
+ @classmethod
+ def get_status(cls) -> Dict:
+ """Get SpamAssassin installation and running status."""
+ installed = False
+ running = False
+ enabled = False
+ version = None
+ milter_installed = False
+ milter_running = False
+
+ try:
+ installed = PackageManager.is_installed('spamassassin')
+ if installed:
+ running = ServiceControl.is_active('spamassassin')
+ enabled = ServiceControl.is_enabled('spamassassin')
+ result = subprocess.run(['spamassassin', '--version'], capture_output=True, text=True)
+ match = re.search(r'version\s+(\S+)', result.stdout)
+ if match:
+ version = match.group(1)
+
+ # Check milter
+ milter_installed = PackageManager.is_installed('spamass-milter')
+ if milter_installed:
+ milter_running = ServiceControl.is_active('spamass-milter')
+ except (subprocess.SubprocessError, FileNotFoundError):
+ pass
+
+ return {
+ 'installed': installed,
+ 'running': running,
+ 'enabled': enabled,
+ 'version': version,
+ 'milter_installed': milter_installed,
+ 'milter_running': milter_running,
+ }
+
+ @classmethod
+ def install(cls) -> Dict:
+ """Install SpamAssassin and spamass-milter."""
+ try:
+ manager = PackageManager.detect()
+ if manager == 'apt':
+ packages = ['spamassassin', 'spamass-milter', 'spamc']
+ else:
+ packages = ['spamassassin', 'spamass-milter-postfix']
+
+ result = PackageManager.install(packages, timeout=300)
+ if result.returncode != 0:
+ return {'success': False, 'error': result.stderr or 'Failed to install SpamAssassin'}
+
+ # Enable spamd on Debian/Ubuntu
+ if manager == 'apt' and os.path.exists(cls.SPAMASSASSIN_DEFAULT):
+ result = run_privileged(['cat', cls.SPAMASSASSIN_DEFAULT])
+ content = result.stdout or ''
+ content = re.sub(r'ENABLED=0', 'ENABLED=1', content)
+ content = re.sub(r'CRON=0', 'CRON=1', content)
+ run_privileged(['tee', cls.SPAMASSASSIN_DEFAULT], input=content)
+
+ # Configure milter to listen on port 8893
+ milter_config = 'OPTIONS="-u spamass-milter -i 127.0.0.1 -p inet:8893@localhost -- --socket=/var/run/spamassassin/spamd.sock"\n'
+ if os.path.exists(cls.SPAMASS_MILTER_DEFAULT):
+ run_privileged(['tee', cls.SPAMASS_MILTER_DEFAULT], input=milter_config)
+
+ # Write default config
+ cls.configure(cls.DEFAULT_CONFIG)
+
+ # Update rules
+ run_privileged(['sa-update'], timeout=120)
+
+ ServiceControl.enable('spamassassin')
+ ServiceControl.start('spamassassin', timeout=30)
+
+ if PackageManager.is_installed('spamass-milter'):
+ ServiceControl.enable('spamass-milter')
+ ServiceControl.start('spamass-milter', timeout=30)
+
+ return {'success': True, 'message': 'SpamAssassin installed successfully'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def configure(cls, settings: Dict = None) -> Dict:
+ """Write SpamAssassin configuration."""
+ try:
+ config = dict(cls.DEFAULT_CONFIG)
+ if settings:
+ config.update(settings)
+ content = cls.LOCAL_CF_TEMPLATE.format(**config)
+ run_privileged(['tee', cls.SPAMASSASSIN_CONF], input=content)
+ return {'success': True, 'message': 'SpamAssassin configured'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_config(cls) -> Dict:
+ """Get current SpamAssassin configuration."""
+ try:
+ if not os.path.exists(cls.SPAMASSASSIN_CONF):
+ return {'success': True, 'config': dict(cls.DEFAULT_CONFIG)}
+
+ result = run_privileged(['cat', cls.SPAMASSASSIN_CONF])
+ content = result.stdout or ''
+
+ config = dict(cls.DEFAULT_CONFIG)
+
+ # Parse values
+ score_match = re.search(r'required_score\s+(\S+)', content)
+ if score_match:
+ config['required_score'] = float(score_match.group(1))
+
+ report_match = re.search(r'report_safe\s+(\d+)', content)
+ if report_match:
+ config['report_safe'] = int(report_match.group(1))
+
+ subject_match = re.search(r'rewrite_header Subject\s+(.+)', content)
+ if subject_match:
+ config['rewrite_subject'] = subject_match.group(1).strip()
+
+ bayes_match = re.search(r'use_bayes\s+(\d+)', content)
+ if bayes_match:
+ config['use_bayes'] = int(bayes_match.group(1))
+
+ auto_learn_match = re.search(r'bayes_auto_learn\s+(\d+)', content)
+ if auto_learn_match:
+ config['bayes_auto_learn'] = int(auto_learn_match.group(1))
+
+ rbl_match = re.search(r'skip_rbl_checks\s+(\d+)', content)
+ if rbl_match:
+ config['skip_rbl_checks'] = int(rbl_match.group(1))
+
+ return {'success': True, 'config': config}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def update_rules(cls) -> Dict:
+ """Update SpamAssassin rules."""
+ try:
+ result = run_privileged(['sa-update'], timeout=120)
+ # sa-update returns 0 for updates, 1 for no updates, 2+ for errors
+ if result.returncode <= 1:
+ ServiceControl.restart('spamassassin', timeout=30)
+ return {
+ 'success': True,
+ 'message': 'Rules updated' if result.returncode == 0 else 'Rules already up to date',
+ 'updated': result.returncode == 0,
+ }
+ return {'success': False, 'error': result.stderr or 'Update failed'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def train_spam(cls, message_path: str) -> Dict:
+ """Train SpamAssassin with a spam message."""
+ try:
+ result = run_privileged(['sa-learn', '--spam', message_path])
+ if result.returncode == 0:
+ return {'success': True, 'message': 'Message learned as spam'}
+ return {'success': False, 'error': result.stderr or 'Training failed'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def train_ham(cls, message_path: str) -> Dict:
+ """Train SpamAssassin with a ham (non-spam) message."""
+ try:
+ result = run_privileged(['sa-learn', '--ham', message_path])
+ if result.returncode == 0:
+ return {'success': True, 'message': 'Message learned as ham'}
+ return {'success': False, 'error': result.stderr or 'Training failed'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_stats(cls) -> Dict:
+ """Get SpamAssassin Bayes statistics."""
+ try:
+ result = run_privileged(['sa-learn', '--dump', 'magic'])
+ output = result.stdout or ''
+ stats = {
+ 'nspam': 0,
+ 'nham': 0,
+ 'ntokens': 0,
+ }
+ for line in output.splitlines():
+ parts = line.split()
+ if len(parts) >= 4:
+ if parts[2] == 'nspam':
+ stats['nspam'] = int(parts[1])
+ elif parts[2] == 'nham':
+ stats['nham'] = int(parts[1])
+ elif parts[2] == 'ntokens':
+ stats['ntokens'] = int(parts[1])
+
+ return {'success': True, 'stats': stats}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def reload(cls) -> Dict:
+ """Reload SpamAssassin."""
+ try:
+ result = ServiceControl.restart('spamassassin', timeout=30)
+ if result.returncode == 0:
+ return {'success': True, 'message': 'SpamAssassin restarted'}
+ return {'success': False, 'error': result.stderr or 'Restart failed'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}