Send Custom Notifications from scripts running on a Synology [new]

This is an update of a old post written for DSM 4 and 5: how to use the native Notification Mechanism of Synology to sent custom notifications. It’s now tested on my DS1815+ with DSM 6.0.

Click to Read More

First, define the Notifications to be sent:

  1. Open a dos command prompt, and execute: telnet <YourSynoHostname>
    1. As an alternative, I am using the free telnet client “Putty” to open SSH Console.
  2. Login as administrator
  3. Once connected via telnet, enter the root mode with the command ‘sudo -i’, using here alsoย the password of your administrator
  4. Execute next: cdย /usr/syno/synoman/webman/texts/
  5. Execute: ls
  6. Now you see a list of folders for each language supported by your Synology. You must at least defined your custom notifications inย theย ‘enu’ version and next the version that match your language.
  7. Copy the file with the definition of the existing notifications in a shared folder to edit it easily: cp enu/mails /volume1/web/
    1. I presume here that the web station is enabled, otherwise, copy the file ‘mails’ in any other shared folder.
    2. As an alternative, you can use the Package “Config File Editor” to edit “/usr/syno/synoman/webman/texts/enu/mails”
  8. Edit now this file ‘mails’ (e.g.: with notepad++: \\<yourSynoHostname>\web\mails)
  9. Add your new custom “tags” at the end of the file with an adequate definition (see bellow for an example). You must specify a Title, a Subject, the text, and a Category with its priority. The category is used to group the Notifications in the DSM > Control Panel > Notification > Advanced Tab. For each Category, specify one of the possible values with a “Priority”, separated by a coma. The priority is used to filter the notifications in the “Advanced” tab (Look at existing tags in the file forย illustration):
    1. Possible values for “Category”
      1. Backup/Restore: group under ‘Backup and Restoration’ in the “Advanced” tab
      2. CMS
      3. External Storage
      4. HA: grouped under ‘High-availability cluster’
      5. AHA: notย displayed inย the “Advanced” tab but related to External Storage
      6. Storage: grouped under ‘Internal Storage’
      7. USB Copy: notย displayed inย the “Advanced” tab but related to External Storage
      8. Power System: grouped under ‘Power supply’
      9. System
      10. PerfEvent: notย displayed inย the “Advanced” tab but related to System
    2. Possible values for “Priority”
      1. Important: displayed as Critical
      2. (no value): displayed as Informative
        Synology Notifications
        Synology Notifications
  10. Save your changes (E.g.: back to the telnet console, execute:ย cp /volume1/web/mails enu/mails)

Examples:

[MySqlBkpError]

Category: Backup/Restore,Important
Title: Database backup failed
Subject: Database backup on %HOSTNAME% has failed

Dear User,

Database backup on %HOSTNAME% has failed.

[MySqlBkpOK]

Category: Backup/Restore
Title: Database backupย completed
Subject: Database backup on %HOSTNAME% has succeeded

Dear User,

Database backup on %HOSTNAME% has successfully completed.

Next,ย define how to sent those custom Notificationsย if and only if they are in a Category which does not appear in the “Advanced” tab of the “Control Panel” > “Notifications” pane > “Advanced” tab (Ex.: the categoryPerfEvent). It’s indeed via that Tab that you should to enable ย the desiredย delivery modes: “email”, “sms”, …. which is obviously only possible for Notifications in a Category which is displayed.

  1. Go back to the telnet console and execute: cp /usr/syno/etc/notification/notification_filter.settings /volume1/web/

    1. As an alternative, you can use the Package “Config File Editor” to edit “/usr/syno/etc/notification/notification_filter.settings”
  2. Edit the file ‘notification_filter.settings’ (E.g. with notepad++)
  3. At the end of that file, insert a configuration line for each custom tag, specifying how the notification must be sent (Look at the other line for illustrations). Possible delivery mode are:
    1. mail
    2. sms
    3. mobile
    4. cms: this is the native popup notification mechanism of DSM, enabled by default for all notifications
    5. msn: not supported anymore since 17th July 2014
    6. skype: not supported anymore since 17th July 2014
  4. Copy the file back to its original location:ย cp /volume1/web/notification_filter.settings /usr/syno/etc/

Examples:

MySqlBkpOK=”mail”

MySqlBkpError=”mail”

Now, reboot your Synology

It seems that in the past, I was able to apply my changes in thoseย files without a reboot. But while testingย this trick on DSM 6.x, I didn’t findย how to do itย without a reboot.

Finally, modify your script to sent your notifications:

  1. Edit your script (E.g. with notepad++).
  2. Add where required the following command:ย /usr/syno/bin/synonotify <YourCustomTag>
  3. Save your changes.

In the example here after, I sent notifications depending on the success or failure of the previous command:

if [ $? -eq 0 ] then /usr/syno/bin/synonotifyย MySqlBkpOK
else /usr/syno/bin/synonotifyย MySqlBkpError
fi

Finally, check that the “Notifications” are enabled on your Synology and tick options like emails, SMS, … for the new tags if required:

  1. In your DSM, go to โ€œControl Panelโ€ > โ€œNotificationโ€ > โ€œE-Mailโ€
  2. Tick the option โ€œEnable e-mail notificationsโ€.
  3. Complete all the fields in that tab. At least: SMTP server, SMTP port, SMTP authentication and Primary email.
  4. Send also a test mail from this tab to verify your settings.
  5. Go next to the “Advanced” tab
  6. Tick the “E-mail” option (and possibly others) for the new tags which appear now in the list.
    1. If the tags do not appear, close and reopen the control panel.ย restart your DSM!
    2. The tags appear with their Title under their Category
Notifications Configuration
Notifications Configuration

And here are the outcomes: a popup message and an email

Database Backup Email
Database Backup Email
Database Backup Custom Notification
Database Backup Custom Notification

Pay attention that the tags are case sensitive ! Also backup the changes you made in the file ‘mails’ and ‘notification_category’ as they will be overwritten for sure when you will update the DSM… Finally, delete the files ‘mails’ and ‘notification_category’ from your web folder…

Notice: the user EConceptApplications suggestedย on Synology Forum to useย a script as here under to automatically reinsert the notifications

grep -q “MySqlBkpOK” /usr/syno/etc/notification/notification_filter.settings
if [ $? -ne 0 ] then

echo MySqlBkpOK=”mail” >> /usr/syno/etc/notification/notification_filter.settings

fi

Notice: a reader,ย k13tas, suggested thatย it wasย much easier to reuse an existing notification tag and customize its text via Control Panel > Notification > Advanced. Indeed, those changes are not lost after a DSM update.

Notice: aย reader, Rusmin,ย posted here that he found how to pass parameters to be used ย in the notification message, via a hash json string. In his sample, one passes the value “value1” via a variable named %VAR1%. The value can obviously come from any variable of your shell script. Ex.: $PPID, $MyVariable, $$, etc…

Usage: /usr/syno/bin/synonotify tag_event [hash_json_string]

/usr/syno/bin/synonotify Tag_Name ‘{“[%VAR1%]”: “value1”, “[%VAR2%]”: “value2”}’

NB: another reader, Paul Marcos, reports however that for him:

this wouldn’t work with the brackets:

/usr/syno/bin/synonotify Tag_Name ‘{“[%VAR1%]”: “value1”}’

but this, without the brackets would:

/usr/syno/bin/synonotify Tag_Name ‘{“%VAR1%”: “value1”}’

Loading


Categories:

Tags:


Comments

34 responses to “Send Custom Notifications from scripts running on a Synology [new]”

  1. Josep Avatar
    Josep

    In DSM 6.0.2 update 6 your solution doesn’t work.

    1. Valery Letroye Avatar

      I have right now the version “6.0.2-8451 Update 6” on my NAS and this notification trick is still working.
      Do you have an error message while executing for example “/usr/syno/bin/synonotify MySqlBkpOk” ?

  2. Jan Avatar
    Jan

    Thanks for this great tutorial. One small typo. You’re missing a ; in shell script.
    I used your tutorial to check the validness of an EPG XML file (which is used by DVBLogic’s DVBLink for IPTV) and send me a warning when it doesn’t:
    python -c “import sys, xml.dom.minidom as d; d.parse(sys.argv[1])” “$1” > /tmp/xmlcheck.txt 2>&1
    grep -q -i “error” /tmp/xmlcheck.txt
    if [ $? -eq 0 ]; then
    /usr/syno/bin/synonotify XMLTVNotValid
    echo “XML \”$1\” is *NOT* valid”
    else
    echo “XML \”$1\” is valid”
    fi

  3. Rusmin Avatar
    Rusmin

    Thanks for the tutorial! this really helps me a lot.

    I also found out that we can send custom values for the Variables.
    For example this is what I use to inform when my dynamic IP got changed :

    jsonstr=”{‘[%IP_CHANGED%]’: ‘$ip’}”
    /usr/syno/bin/synonotify MyIPChanged “$jsonstr”

    the last optional parameter is in hash json string format.

    i.e: /usr/syno/bin/synonotify Tag_Name โ€˜{โ€œ[%VAR1%]โ€: โ€œvalue1โ€, โ€œ[%VAR2%]โ€: โ€œvalue2โ€}โ€™

    I’m using DSM 6.1-15047 Update 1

    1. Valery Letroye Avatar

      Great finding! Thx a lot for sharing.

      V.

      1. Jan Avatar
        Jan

        Well I can’t get it working. I have following section in mails:
        [FailedRecording]
        Category: System,Important
        Title: Failed recording
        Subject: Failed recording

        There was a failed recording:
        %FILENAME%

        I am running a shell script once a day that checks if there are failed recordings. When found it will call:
        /usr/syno/bin/synonotify FailedRecording {FILENAME:”test”}

        But it doesn’t work. I tried many variations like:
        /usr/syno/bin/synonotify FailedRecording {“[FILENAME]”:”test”}
        /usr/syno/bin/synonotify FailedRecording {[FILENAME]:”test”}
        /usr/syno/bin/synonotify FailedRecording {%FILENAME%:”test”}
        /usr/syno/bin/synonotify FailedRecording {[%FILENAME%]:”test”}
        /usr/syno/bin/synonotify FailedRecording {“[%FILENAME%]”:”test”}

        1. Jan Avatar
          Jan

          Noticed that a space between : and “test” is NOT allowed, Synonotify will not run and gives an “error” message:
          Copyright (c) 2003-2017 Synology Inc. All rights reserved.

          Usage: /usr/syno/bin/synonotify tag_event [hash_json_string]

          So this is accepted (but still doesn’t work):
          /usr/syno/bin/synonotify FailedRecording โ€˜{โ€œ[%FILENAME%]โ€:โ€œvalue1โ€}โ€™
          This is not accepted:
          /usr/syno/bin/synonotify FailedRecording โ€˜{โ€œ[%FILENAME%]โ€: โ€œvalue1โ€}โ€™

  4. Jan Avatar
    Jan

    Arghhh I succeeded after 100+ variations. This is the lucky one:
    /usr/syno/bin/synonotify FailedRecording “{\”%FILENAME%\”: \”bla\”}”

    The variable %FILENAME% in my custom message defined in /usr/syno/synoman/webman/texts/enu/mails is replaced with bla!

    1. Valery Letroye Avatar

      Thx for the feedback!
      I think that the notation of Rusmin was ok but WordPress is transforming the single quote in this symbol: ‘
      This symbol ‘ is not valid for a shell script. Reason why you replaced it with a double quote. As a consequence, all inner double quotes must be escaped with a .

      I will update my post to replace the ‘ and ” by ' (& #39;) and " (& #34;)

      V.

  5. fabioman Avatar

    A really useful tip, thanks. Should be in the common features of DSM. I added this to /usr/syno/synoman/webman/texts/enu/mails:
    ———-
    [ASiteIsDown]
    Category: System
    Title: A website is down
    Subject: The website [%SITENAME%] is down

    Dear user,

    The website [%SITENAME%] did not respond.
    ———
    and via email works, but on DS finder (android) it shows “ASiteIsDown” instead of “The website blabla is down”. I edited /usr/syno/synoman/webman/texts/enu/mails, /usr/syno/synoman/webman/texts/ita/mails for safety, and /usr/syno/etc/notification/notification_filter.settings
    What am I missing?

    1. Valery Letroye Avatar

      I never used the DS Finder before… After reading your post, I installed it to have a look. I did next create a custom notification and enabled the sending mode “mobile” on it. I can now reproduce your error but have no clue how to fix it… I will try to investigate further if possible…

      What I can already tell, is that the text of the notification is not the “Subject” read from enu/mails. Indeed, if I change the subject of another notification (ex.: ext4_fs_err), I see that this change is not taken into account. Even after a reboot, I still receive the old message of that notification.

  6. Peter Fritsen Avatar
    Peter Fritsen

    Nothing less than perfect! Thanks for a great guide! ๐Ÿ™‚
    Just for info: on a DS214Play, DSM 6.1.7-15284 i can send both mail, sms and desktop notifications when following this guide. I have used ‘Backup/Restore’ as category and ‘Important’ priority – I have not tested other settings.

  7. Christopher H. Avatar

    hi, it’s my first try creating custom notifications. I have little problems trying this guide – what i have done by now:

    1.) login by shell into my synology
    2.) sudo vi /usr/syno/synoman/webman/texts/enu/mails
    3.) added at the bottom (two blank lines above, one under it):
    [RsyncStart]
    Category: System
    Title: synchronising to usb drive started
    Subject: rsync process started to synchronise data for backup
    Dear user,
    sync job has been started.
    regards
    4.) added the same into language file (only ger):
    sudo vi /usr/syno/synoman/webman/texts/ger/mails
    5.) try’d to test (does not work):
    /usr/syno/bin/synonotify RsyncStart

    So, am i anything missing? What i saw that i don’t have a file like notification_category as mentioned in an earlier post….
    pls hlp thx

    1. Christopher H. Avatar

      added also – but still not working (no message):
      sudo vi /usr/syno/etc/notification/notification_filter.settings
      RsyncStart=”mail,sms,mobile,msn,skype,cms”
      RsyncStatus=”cms”
      RsyncDone=”mail,sms,mobile,msn,skype,cms”

      note: above there was a little mistake i changed for two languages enu and ger therefore little mixed up point 2 and 4 with lang variables. This is not the error.

      this works: /usr/syno/bin/synonotify AutoBlockAdd (tested, therefore no broken message system)

  8. Christopher H. Avatar

    ok. solved restart of diskstation is needed to see all changes.

    1. Valery Letroye Avatar

      Happy to see it worked ๐Ÿ˜‰

  9. Phong Chiem Avatar
    Phong Chiem

    Thank you very much for this tutorial!

  10. hirasawa Avatar
    hirasawa

    Good tutorial, still working with DSM 6.2.2-24922 Update 6

  11. Jip-Hop Avatar

    Great guide! Working on my DS918+ with DSM 6.2.3-25426 Update 3. I’m using this method in my “Autorun Synology Hyper Backup and Integrity Check with Email Notifications” script: https://gist.github.com/Jip-Hop/b9ddb2cc124302a5558659e1298c36ec.

  12. Rick Avatar
    Rick

    Awesome! Took me some time to find a way to reliably send emails from bash scripts, but this works nicely. Didn’t even bother adding a template, as mentioned by @Jip-Hop just abusing one of the variables works for me ๐Ÿ™‚

  13. Paul M Avatar
    Paul M

    Add me to the chorus of folks with thanks for this article (and all the comment followups)! It took me some time to get this working on my DiskStation, but I was able to. I’m currently running DSM 6.2.4-25556.

    The thing that tripped me up was the formatting of the JSON for parameters. No matter what I did, the parameters wouldn’t get substituted. However, looking at Jip-Hop’s gist, I saw that they didn’t include the square brackets around the parameter names, and that was the problem I had. That is, this wouldn’t work:

    /usr/syno/bin/synonotify Tag_Name ‘{“[%VAR1%]”: “value1”}’

    but this would:

    /usr/syno/bin/synonotify Tag_Name ‘{“%VAR1%”: “value1”}’

    Once I made that switch, I started getting emails and push notifications from my script. Thanks again for this post, it saved me tons of time and makes my script notifications infinitely more useful.

    1. Valery Letroye Avatar

      Thx a lot for the feedback Paul. I did update the post accordingly.

      v.

    2. Laurent Avatar
      Laurent

      Hello,
      very good script but…
      what if value1 is a variable ?
      I cannot manage to insert it into the json string ….

      this work fine :
      /usr/syno/bin/synonotify VPN_DOWN4EVER ‘{“%VPNERROR%”: “text of the error”}’

      but this doesn’t :
      errorReconnectVPN=$(tail -n 10 /var/log/messages | grep ‘synovpn’)
      /usr/syno/bin/synonotify VPN_DOWN4EVER ‘{“%VPNERROR%”: “$errorReconnectVPN”}’

      Someone can help please ?
      thanks
      Laurent

      1. Valery Letroye Avatar

        I presume that you get a notification with this variable name “$errorReconnectVPN” in the message instead of its actual value…
        This is because the single quotes prevent the variable expansion.
        Check this: echo ‘{“%VPNERROR%”: “$errorReconnectVPN”}’

        Try this :
        ~# value=”xxx”
        ~# /usr/syno/bin/synonotify HotSpareDiskPlugout ‘{“%DISK_ID%”: “$value”}’
        ~# /usr/syno/bin/synonotify HotSpareDiskPlugout ‘{“%DISK_ID%”: “‘$value’”}’

        The second one will work as you expect.

        Or you actually don’t get the notification ? <= are you sure you have access to read /var/log/messages ? (it's protected)

        1. Matt Avatar
          Matt

          The additional single quotes around the variable fixed this for me, thanks!

          1. Matt Avatar
            Matt

            Sorry, quick correction – the additional single quotes worked in the CLI, but I had to add an extra layer of double quotes to work inside the bash script.

            So my successful implementation was as follows:
            /usr/syno/bin/synonotify tag_event ‘{“%VAR%”: “‘”$var”‘”}’

  14. Daniel Goepp Avatar
    Daniel Goepp

    I am running DSM 7.0 and I noticed a few things when getting this setup. I’m not sure if they apply to previous versions as this is the first time I have played with this. These instructions were great! However, I did noticed something in my setup.

    First, if you edit an existing system notification, it puts it in a different location: /usr/syno/etc/notification/mails
    I found it to be easier and safer to just put my custom notifications here.

    Also, when searching for examples I was looking for docker notifications, and was not seeing them in the default location of: /usr/syno/synoman/webman/texts/enu/mails instead they were in: /usr/syno/synoman/webman/3rdparty/Docker/texts/enu/mails. So if anyone here is having a hard time finding other notifications, you might check the 3rdparty folder.

    Finally, I did not find I needed to restart. Perhaps they fixed this again in 7.0 ๐Ÿ™‚ I dunno.

    1. Valery Letroye Avatar

      I didn’t try yet this on DSM 7.0 myself… So thx for the feedback !

      V.

  15. Alessio Avatar
    Alessio

    Everything works perfectly, thank you very much, soon I will try it for DSM 7.0 too. I wanted to ask if it was possible to send a notification only for a specific user.

    1. Valery Letroye Avatar

      I never tried myself…

      But: as users may subscribe (or not) on events to be notified, via Control Panel > Notifications > Advanced
      I would suggest that: if you want only one user to be notified, tell that one only to subscribe on your custom notifications.

  16. TKruzze Avatar
    TKruzze

    This was such a great solution for DSM 6.x, However, I can’t figure out how to make it work under 7.0. I recent;y upgraded my NAS from a DS416 to a 920+ and decided to install 7.0 fresh. So much has changed and despite many attempts and many reboots, I’m not able to add any new Notifications to DSM 7.0. I even tried the suggestions from Daniel Goepp and that didn’t work for me, either.

    Anyway, thanks for putting this out there! If, and when, you make the move to DSM 7.x, I do hope you’ll share any solutions you come up with. I feel absolutely lost without it. Hijacking an used notification works, to a degree, but I really miss having the Desktop notification flow displaying my custom details.

  17. Nigel Bartlett Avatar
    Nigel Bartlett

    Hi, I wrote a bash function to call synonotify (below). I have tested it on DSM 6.2 and DSM 7.1.

    #!/bin/bash

    # Send a notification email via the NAS. Parameters are: TAG_EVENT VARLIST value1 value2 value3 …
    # Tested on DSM 6.2.4-25556 Update 6 and DSM 7.1.1-42962 Update 2
    function nas_notify()
    {
    # TAG_EVENT names the email template to be used (see /usr/syno/synoman/webman/texts/enu/mails for the English list)
    local TAG_EVENT=${1}
    # VARLIST is the list of variables used in the email template (without the surrounding % signs)
    # Note: Some variables, eg HOSTNAME, are set by the NAS and shouldn’t be included here
    local VARLIST=${2}
    # The values to be assigned to the variables in the above list are in $3 $4 $5 …
    local NTFYJSON V VAL
    # Values start at this parameter
    local I=3
    # This command does the notify
    local NTFY_CMD=”/usr/syno/bin/synonotify”
    # Create the variable/value list in almost JSON format. The NAS surrounds each variable name with % signs so we do, too
    if [ “${VARLIST}” != “” ]; then
    for V in ${VARLIST}; do
    eval VAL=\$$I
    NTFYJSON=”${NTFYJSON},’%${V}%’: ‘${VAL}’”
    I=$(( I + 1 ))
    done
    # Drop the leading comma from NTFYJSON and enclose the result in braces for actual JSON
    NTFYJSON=”{${NTFYJSON:1}}”
    fi
    [ -x “${NTFY_CMD}” ] && ${NTFY_CMD} “${TAG_EVENT}” “${NTFYJSON}”
    }

    nas_notify “ShareSyncError” “S2S_SERVER S2S_TASK DUR” “${BASH_SOURCE[0]}” “Message about the failure” “0 days 0 hours 0 mins 1 secs”

    exit $?

    1. Valery Letroye Avatar

      Thx a lot for sharing!

    2. Matt Avatar
      Matt

      Unfortunately this doesn’t seem to work with DSM 7.2

Leave a Reply

Your email address will not be published. Required fields are marked *