#!/bin/bash # Add Domain Helper Script # Adds DKIM support and configuration for additional domains set -euo pipefail # Colors RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BLUE='\033[0;34m' NC='\033[0m' # Check arguments if [[ $# -ne 1 ]]; then echo "Usage: $0 " echo "Example: $0 newdomain.com" echo echo "This script will:" echo " - Generate DKIM keys for the new domain" echo " - Update OpenDKIM configuration" echo " - Display DNS records to add" echo " - Show PostfixAdmin setup instructions" exit 1 fi DOMAIN=$1 # Logging LOG_FILE="/var/log/email-server-setup.log" log() { echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE" } info() { echo -e "${BLUE}INFO: $1${NC}" log "INFO: $1" } success() { echo -e "${GREEN}SUCCESS: $1${NC}" log "SUCCESS: $1" } warning() { echo -e "${YELLOW}WARNING: $1${NC}" log "WARNING: $1" } error() { echo -e "${RED}ERROR: $1${NC}" >&2 log "ERROR: $1" exit 1 } # Check if running as root check_root() { if [[ $EUID -ne 0 ]]; then error "This script must be run as root" fi } # Validate domain format validate_domain() { if [[ ! "$DOMAIN" =~ ^[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]*\.[a-zA-Z]{2,}$ ]]; then error "Invalid domain format: $DOMAIN" fi } # Check if domain already exists in DKIM check_existing_domain() { if [[ -d "/etc/opendkim/keys/$DOMAIN" ]]; then warning "DKIM keys already exist for $DOMAIN" read -p "Do you want to regenerate them? (y/N): " -n 1 -r echo if [[ ! $REPLY =~ ^[Yy]$ ]]; then info "Keeping existing DKIM keys for $DOMAIN" return 1 fi fi return 0 } # Get main hostname from existing configuration get_main_hostname() { if [[ -f "/etc/postfix/main.cf" ]]; then MAIN_HOSTNAME=$(grep "^myhostname" /etc/postfix/main.cf | cut -d= -f2 | tr -d ' ') if [[ -z "$MAIN_HOSTNAME" ]]; then error "Could not determine main hostname from Postfix configuration" fi else error "Postfix configuration not found. Run the main setup script first." fi } # Generate DKIM keys for the new domain generate_dkim_keys() { info "Generating DKIM keys for domain: $DOMAIN" # Create directory mkdir -p /etc/opendkim/keys/$DOMAIN # Generate DKIM key opendkim-genkey -t -s mail -d $DOMAIN -D /etc/opendkim/keys/$DOMAIN # Set permissions chown -R opendkim:opendkim /etc/opendkim/keys/$DOMAIN chmod 600 /etc/opendkim/keys/$DOMAIN/mail.private success "DKIM keys generated for $DOMAIN" } # Update OpenDKIM configuration update_opendkim_config() { info "Updating OpenDKIM configuration..." # Check if entry already exists in key.table if ! grep -q "mail._domainkey.$DOMAIN" /etc/opendkim/key.table 2>/dev/null; then echo "mail._domainkey.$DOMAIN $DOMAIN:mail:/etc/opendkim/keys/$DOMAIN/mail.private" >> /etc/opendkim/key.table fi # Check if entry already exists in signing.table if ! grep -q "*@$DOMAIN" /etc/opendkim/signing.table 2>/dev/null; then echo "*@$DOMAIN mail._domainkey.$DOMAIN" >> /etc/opendkim/signing.table fi # Check if domain already exists in trusted.hosts if ! grep -q "^$DOMAIN$" /etc/opendkim/trusted.hosts 2>/dev/null; then echo "$DOMAIN" >> /etc/opendkim/trusted.hosts fi success "OpenDKIM configuration updated" } # Restart OpenDKIM service restart_opendkim() { info "Restarting OpenDKIM service..." if systemctl restart opendkim; then success "OpenDKIM service restarted" else error "Failed to restart OpenDKIM service" fi } # Test DKIM configuration test_dkim() { info "Testing DKIM configuration..." sleep 2 # Give OpenDKIM time to start if opendkim-testkey -d $DOMAIN -s mail -vvv 2>&1 | grep -q "key OK"; then success "DKIM test passed for $DOMAIN" else warning "DKIM test failed. Check the DNS record below and try again later." fi } # Display DNS records to add display_dns_records() { get_main_hostname echo echo -e "${YELLOW}=== DNS Records to Add for $DOMAIN ===${NC}" echo echo -e "${BLUE}1. MX Record:${NC}" echo "MX $DOMAIN $MAIN_HOSTNAME" echo echo -e "${BLUE}2. SPF Record:${NC}" echo "TXT $DOMAIN \"v=spf1 mx ~all\"" echo echo -e "${BLUE}3. DMARC Record:${NC}" echo "TXT _dmarc.$DOMAIN \"v=DMARC1; p=none; rua=mailto:dmarc@$DOMAIN\"" echo echo -e "${BLUE}4. DKIM Record:${NC}" echo "Record name: mail._domainkey.$DOMAIN" echo "Record type: TXT" echo "Record value:" cat /etc/opendkim/keys/$DOMAIN/mail.txt 2>/dev/null || echo "Error: DKIM key file not found" echo } # Display PostfixAdmin instructions display_postfixadmin_instructions() { get_main_hostname echo -e "${YELLOW}=== PostfixAdmin Setup Instructions ===${NC}" echo echo "1. Visit: https://$MAIN_HOSTNAME/postfixadmin/" echo "2. Login with your admin credentials" echo "3. Go to 'Domain List' → 'New Domain'" echo "4. Enter domain: $DOMAIN" echo "5. Set desired limits and quotas" echo "6. Click 'Add Domain'" echo "7. Create mailboxes under 'Virtual List' → 'Add Mailbox'" echo echo -e "${BLUE}Suggested mailboxes for $DOMAIN:${NC}" echo " - admin@$DOMAIN" echo " - info@$DOMAIN" echo " - noreply@$DOMAIN" echo " - support@$DOMAIN" echo } # Display application configuration display_app_config() { get_main_hostname echo -e "${YELLOW}=== Application SMTP Configuration ===${NC}" echo echo "Your applications can now send email from $DOMAIN using these settings:" echo echo -e "${BLUE}SMTP Settings:${NC}" echo " Host: $MAIN_HOSTNAME" echo " Port: 587 (STARTTLS) or 465 (SSL/TLS)" echo " Security: STARTTLS or SSL/TLS" echo " Username: mailbox@$DOMAIN (full email address)" echo " Password: [mailbox password from PostfixAdmin]" echo echo -e "${BLUE}Example Python code:${NC}" cat << 'EOF' import smtplib from email.mime.text import MIMEText smtp_config = { 'host': 'MAIN_HOSTNAME', 'port': 587, 'username': 'app@DOMAIN', 'password': 'your_mailbox_password' } msg = MIMEText("Hello from DOMAIN!") msg['Subject'] = "Test Email" msg['From'] = smtp_config['username'] msg['To'] = "recipient@example.com" with smtplib.SMTP(smtp_config['host'], smtp_config['port']) as server: server.starttls() server.login(smtp_config['username'], smtp_config['password']) server.send_message(msg) EOF echo } # Verify email server is running verify_email_server() { info "Verifying email server status..." services=("postfix" "dovecot" "opendkim" "postgresql") all_running=true for service in "${services[@]}"; do if ! systemctl is-active --quiet $service; then warning "$service is not running" all_running=false fi done if $all_running; then success "All required services are running" else warning "Some services are not running. You may need to restart them." fi } # Main function main() { echo -e "${BLUE}Add Domain Script for Email Server${NC}" echo "==================================" echo "Adding domain: $DOMAIN" echo check_root validate_domain verify_email_server if check_existing_domain; then generate_dkim_keys fi update_opendkim_config restart_opendkim test_dkim display_dns_records display_postfixadmin_instructions display_app_config echo success "Domain $DOMAIN has been configured!" echo echo -e "${YELLOW}Next steps:${NC}" echo "1. Add the DNS records shown above" echo "2. Wait for DNS propagation (up to 24 hours)" echo "3. Add the domain in PostfixAdmin" echo "4. Create mailboxes for the domain" echo "5. Test email sending and receiving" echo echo -e "${BLUE}To test the configuration later, run:${NC}" echo "./test-email-server.sh" } # Show help if requested if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then echo "Add Domain Script for Email Server" echo "=================================" echo echo "Usage: $0 " echo echo "This script adds DKIM support for additional domains to your email server." echo "It will generate DKIM keys, update OpenDKIM configuration, and provide" echo "DNS records and PostfixAdmin instructions." echo echo "Examples:" echo " $0 newcompany.com" echo " $0 mysite.org" echo echo "Prerequisites:" echo " - Email server must be already set up with setup-email-server.sh" echo " - Must be run as root" echo " - Domain should point to your server" echo echo "After running this script:" echo " 1. Add the provided DNS records" echo " 2. Configure the domain in PostfixAdmin" echo " 3. Create mailboxes for the new domain" exit 0 fi main "$@"