#!/bin/bash
#
# A simple wrapper script to s-nail. Needs a suitable smarthost.
# A copy of sent mail is saved in the /var/mail/$USER mbox file.
# It is recommended to rotate these files e.g via /etc/logrotate.d.
# See also https://manpages.ubuntu.com/manpages/focal/man1/s-nail.1.html

# SMTP settings - feel free to adjust.
#
# Sender's address is fixed - pay attention to the SPF DNS record!
FROM="no-reply@example.com"
# Default recipient(s), delimited by space.
TO="sysadmin@example.com webadmin@example.com"
SMTP_SERVER="mail.example.com"
# smtp (for tcp/25), smtps (for tcp/465), submission (for tcp/587).
SMTP_PROTO="submission"
# URL escaping required for special characters below.
SMTP_USER="no-reply%40example.com"
SMTP_PASS="topsecret"

# s-nail call.
#
if [ -x "/bin/s-nail" ]; then
    # The recipient's address is the last argument.
    recipient="${@: -1}"
    set -- "${@: 1: $#-1}"
    # Our scripts may send mails to the local user.
    # In this case, we need replace the recipient address.
    [[ "$recipient" = "$USER" ]] && recipient="$TO"
    [[ "$recipient" = "$USER@$HOSTNAME" ]] && recipient="$TO"
    if [ -n "$recipient" ]; then
    "/bin/s-nail" -S from="$FROM" -S v15-compat \
	          -S smtp-auth="login" $([[ "$SMTP_PROTO" = "submission" ]] && echo "-S smtp-use-starttls") \
	          -S mta="$SMTP_PROTO://$SMTP_USER:$SMTP_PASS@$SMTP_SERVER" \
	          -S record="/var/mail/$USER" \
	          "${@}" $recipient
    fi
fi
