Ahh sorry - yes I see loads of errors in the openhab.log. This script worked in openhab 3.2.0 - where i placed it manually in /etc/openhab2/rules - is it wrong to use the UI to add the script ?
What you pasted above is meant to be saved as a file, for a file-based rule.
UI based rules are different. You define the triggers through the UI and the type in the body of the rule. The body is just what’s inside the “then … end” block, without the “then” and “end” lines.
as mentioned above create a rule (not a script) under settings rules with trigger time event.
If you use Blockly you got everything at hand (e.g. logging under openhab - logging and output) without the problem of syntax errors. And you can see the code too (button bottom right) if you prefer to write code. But almost everything can be realized in Blocky too.
Another possibility would be to use the inline-script-block (under run&process) that can hold any Javascript-code.
I never tried sending mails with openhab as I use telegram for any kind of notification which works great with openhab.
But I get this error in openhab.log when I run it ??
“2024-09-08 18:20:58.280 [ERROR] [internal.handler.ScriptActionHandler] - Script execution of rule with UID ‘send_mail_on_low_bat_blocky’ failed: org.graalvm.polyglot.PolyglotException: TypeError: invokeMember (getItem) on org.openhab.core.internal.items.ItemRegistryImpl@1d09e97e failed due to: Cannot convert ‘[object Object]’(language: JavaScript, type: g) to Java type ‘java.lang.String’: Invalid or lossy primitive coercion.”
You cannot compare two strings in this way. They need to be converted to numbers like this:
if battery.numericState < 0.75
See documentation how this can be achieved with blockly.
Just as a side note, the first if-loop is irrelevant as a numericState which is < 0.75 is always not null.
Not sure if this is intended but your script will in worst case send as many separate emails as you have battery items. And each null item will send the message of the last non-null item again.
Take a look, you just need one single if-loop whithin forEach-loop.
Another recommendation could be to add a filter expression to your forEach loop so that you are only dealing with items < 0.75 in your loop.