#!/bin/bash
set -e
echo "== Proxmox SMTP Notification Setup (Postfix) =="
# ─────────────────────────────────────────────
# 1. User Input
# ─────────────────────────────────────────────
read -rp "FQDN of this host (e.g. pve01.example.com): " FQDN
read -rp "Your domain name (e.g. example.com): " MAILDOMAIN
read -rp "SMTP relay server (e.g. smtp.example.com): " SMTPRELAY
read -rp "SMTP relay port (e.g. 587): " SMTPPORT
read -rp "SMTP username: " SMTPUSER
read -rsp "SMTP password: " SMTPPASS
echo
read -rp "Test recipient email (e.g. admin@example.com): " MAILTO
# ─────────────────────────────────────────────
# 2. Set system hostname
# ─────────────────────────────────────────────
echo "[+] Setting system hostname to $FQDN"
hostnamectl set-hostname "$FQDN"
# ─────────────────────────────────────────────
# 3. Install postfix and mail utilities
# ─────────────────────────────────────────────
echo "[+] Installing postfix and mailutils..."
apt update && DEBIAN_FRONTEND=noninteractive apt install -y postfix mailutils
# Set mailname (used as sender domain)
echo "$MAILDOMAIN" > /etc/mailname
# ─────────────────────────────────────────────
# 4. Configure Postfix for external relay
# ─────────────────────────────────────────────
echo "[+] Configuring postfix..."
postconf -e "myhostname = $FQDN"
postconf -e "myorigin = /etc/mailname"
postconf -e "relayhost = [$SMTPRELAY]:$SMTPPORT"
postconf -e "smtp_use_tls = yes"
postconf -e "smtp_sasl_auth_enable = yes"
postconf -e "smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd"
postconf -e "smtp_sasl_security_options = noanonymous"
postconf -e "smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt"
# ─────────────────────────────────────────────
# 5. Add SMTP credentials
# ─────────────────────────────────────────────
echo "[+] Writing SMTP credentials..."
echo "[$SMTPRELAY]:$SMTPPORT $SMTPUSER:$SMTPPASS" > /etc/postfix/sasl_passwd
postmap /etc/postfix/sasl_passwd
chmod 600 /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db
# ─────────────────────────────────────────────
# 6. Restart Postfix and send test mail
# ─────────────────────────────────────────────
echo "[+] Restarting postfix..."
systemctl restart postfix
echo "[+] Sending test email to $MAILTO..."
echo "This is a test email from Proxmox host: $FQDN" | mail -s "Proxmox SMTP Test [$FQDN]" "$MAILTO"
echo "[✓] Setup complete. Check your inbox!"