aboutsummaryrefslogtreecommitdiff
path: root/minimailer
blob: 29e30d2c7d60ee3027072d973b0e4fcd9e085351 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env bash
#
# Send mails based on a template and a recipient list using MSMTP.
#
# See also https://hostpresto.com/community/tutorials/how-to-send-email-from-the-command-line-with-msmtp-and-mutt/
#          https://deaddabe.fr/blog/2021/10/06/sending-templated-emails-using-python-and-msmtp/
#

# Example template file
cat > /dev/null <<EOF
To: recipient
From: myself@mydomain
Subject: Email Test using MSMTP from File

Hi $recipient! This is an automated message to remind
that your email $address is in our database.

King regards,
Myself

--
my signature
EOF

# Example recipient list
cat > /dev/null <<EOF
Some One <someone@example.org>
somebody@example.org
EOF

# Parameters
BASENAME="`basename $0`"
BASEDIR="`dirname $0`"
#TEMPLATE="$BASEDIR/message.tmpl"
#RECIPIENTS="$BASEDIR/recipients.lst"
#MSMTP_ACCOUNT="my-smtp-account-from-msmtprc"
TEMPLATE="$1"
RECIPIENTS="$2"
MSMTP_ACCOUNT="$3"

# Checks
if [ -z "$MSMTP_ACCOUNT" ]; then
  echo "usage: $BASENAME <template-file> <recipients-filelist> <msmtp-account-name>"
  echo ""
  echo "example: $BASENAME message.tmpl recipients.lst my-provider"
  echo "check the source code for template and recipient filelist formats"
  exit 1
elif [ ! -e "$TEMPLATE" ] || [ ! -e "$RECIPIENTS" ]; then
  echo "missing config files"
  exit 1
fi

# Dispatch
cat $RECIPIENTS | while read recipient; do
  # Thanks for the quick sed regexp:
  # https://linuxconfig.org/extract-email-address-from-a-text-file
  address="`echo $recipient | sed -r 's/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/\n&\n/ig;s/(^|\n)[^@]*(\n|$)/\n/g;s/^\n|\n$//g;/^$/d'`"

  echo "sending to $address..."

  sed -e "s/\$recipient/$recipient/g" \
      -e "s/\$address/$address/g" $TEMPLATE | \
    msmtp -a $MSMTP_ACCOUNT $address
done