Mail2Signal

Mail-2-Signal Gateway

I’ve got a Hikvision network camera, which (only) can send email notifications and wanted to spice it up a little (that’s why I started this whole gateway stuff).

So as we do have a gateway running, let’s just hook it up to a mail server.

Setup

I use postfix with pipes and aliases. You might want to setup a dedicated instance like I did or re-use/extend your running relay/server. This assumes an already running postfix.

Packages

To process the mails received, we need some packages:

  • mpack: to unpack mime mails (attachements, text)
  • curl: to trigger the web gateway
  • jq: proper json encoding of attachment
apt-get -y install mpack curl jq

Script

Make sure to adjust the variables below ## init.

#!/bin/bash

## init

# define signal-weg-gateway url
SIGNAL_GW="https://user:password@signal-gateway.example.com"
# define recipient
RECIPIENT="+123456789"

# create unique folder per mail
UUID="$(mktemp -d /tmp/XXXXXXXXXX)"

# save mail
cat > "${UUID}/mail"

# check if we received plain text message or multipart message
if grep -q multipart/mixed "${UUID}/mail"; then
  # extract mail
  munpack -C "${UUID}" "${UUID}/mail"
  # get attachement if exists
  FILE="$(find "${UUID}" \( -name '*.jpg' -o -name '*.png' \))"
  # get text message if exists
  MESSAGE="$(find "${UUID}" -name '*.desc')"
else
  sed '1,/^$/d' "${UUID}/mail" > "${UUID}/message"
  MESSAGE="${UUID}/message"
fi

# trigger webhook
echo "sending signal message for "${UUID}"" | systemd-cat -t mail2signal
if [ ! "${MESSAGE}" == "" ]; then
  if [ ! "${FILE}" == "" ]; then
    echo '{"message": '"$(cat "${MESSAGE}" | jq -sR .)"', "attachments": ["'"$(base64 -w 0 "${FILE}")"'"]}' > "${UUID}/payload"
  else
    echo '{"message": '"$(cat "${MESSAGE}" | jq -sR .)"'}' > "${UUID}/payload"
  fi
  curl -X POST -d@"${UUID}/payload" "${SIGNAL_GW}${RECIPIENT}"
fi

# delete mail
rm -rf ""${UUID}""

Place it somewhere reasonable like /usr/local/bin/mail2signal.sh and make it executable.

Postfix Alias

Add something like this to your /etc/aliases (do not forget to run newaliases after each change):

mail2signal: "|/usr/local/bin/mail2signal.sh"