[SOLVED] How to use mail action from new v2 mail binding in jython rule

You nailed it. Thanks!!

1 Like

BTW, I’m doing this on a recent snapshot using the changes you just pushed to openhab2-jython to fix the package names. :+1:

I’ll be pushing the changes for adding the other languages tonight, so hopefully you can test that out tomorrow!

I usually use the sendMail action documented here: https://www.openhab.org/addons/actions/mail/

But I have began learning to code my scripts with Jython and can not figure out how to import the sendMail function into my script. Does anyone know how I can do this?

I am sure I will have a lot more things that I need in the future because all of this is not documented very well. Would be lovely if someone would include optional importing options in the documentation somewhere.

According to the docs this should be all that is needed (I think this uses the openHAB v1.x action):

from core.actions import Mail
Mail.sendMail("someone@example.com", "This is the subject", "This is the message")

When I look at the MQTTv2 example it states ‘no import needed’:

# no import needed
actions.get("mqtt", "mqtt:systemBroker:embedded-mqtt-broker").publishMQTT("test/system/started", "true")

The example above given by Scott uses the Mail binding, do you have the Mail binding installed?

I get this error with that:

ImportError: No module named core

I am running openhab 2.4

I think I only have the mail action installed. Odd that it does not even find core though…

This is indeed a bit strange. The core of the helper libraries is in core. Do you have any rules that do work or is this the first rule you are working on?

This is my first rule. Everything seems to be working so far, except for actions that I am unable to import.

I tried the second option and got this error:

AttributeError: 'javapackage' object has no attribute 'get'

Here is my entire script so that you can see what I am working with.

Everything works but the sendMail:

from org.slf4j import LoggerFactory
logInfo = LoggerFactory.getLogger("org.eclipse.smarthome.automation.log").info
scriptExtension.importPreset("RuleSupport")
scriptExtension.importPreset("RuleSimple")

from core.actions import Mail
sendMail = Mail.sendMail

class TestRule(SimpleRule):
    def execute(self, module, inputs):
        
        #sendTelegram("bot1", "This is a test message.")
        
        if sendMail("example@example.com", "Test Email!", "This is a test email!"):
            logInfo("Test email sent.")
        else:
            logInfo("Failed to send test email!")
        
        logInfo("Ran Test.")

TestRule = TestRule()
TestRule.setTriggers([
    TriggerBuilder.create()
        .withId("TestTrigger")
        .withTypeUID("core.ItemCommandTrigger")
        .withConfiguration(Configuration({
            "itemName": "Test",
            "command": "ON"
        })).build()
])
automationManager.addRule(TestRule)

events.sendCommand("Test", "ON")

logInfo("Script loaded 'test.py'")

I have since replaced that script with this, with the helper files installed:

script_name = "test"
from core.rules import rule
from core.triggers import when
from core.actions import LogAction
def logInfo(message, name = script_name): LogAction.logInfo(name[:23], str(message))
def logWarn(message, name = script_name): LogAction.logWarn(name[:23], str(message))
def logError(message, name = script_name): LogAction.logError(name[:23], str(message))
def logDebug(message, name = script_name): LogAction.logDebug(name[:23], str(message))
from core.actions import Mail, Telegram

def SystemStarted():
    events.postUpdate("Test", "OFF")
    logInfo("Script loaded '" + script_name + ".py'")
#end

@rule(script_name + "." + "Test")
@when("Item Test received command ON")
def TestRule(event):
    events.sendCommand(event.itemName, "OFF")
    
    Telegram.sendTelegram("bot1", "This is a test message.")
    
    if Mail.sendMail("example@example.com", "Test Email!", "This is a test email!"):
        logInfo("Test email sent.")
    else:
        logInfo("Failed to send test email!")
    #end
    
    logInfo("Ran Test.")
#end

SystemStarted()

This line gives an error when I try to import the Mail action. I think this is because it is not imported in the actions.py.

So I installed the Mail binding and configured the SMTP Thing to use gmail and assigned gmail as the Thing Id. I also had to allow the use of less secure apps in my google account.

from core.log import logging, LOG_PREFIX
from core.rules import rule
from core.triggers import when


@rule("Send mail when Test item changed to ON", description="Rule to test sendmail action")
@when("Item Test changed to ON")
def myTestSwitchChanged(event):
    myTestSwitchChanged.log.info("myTestSwitchChanged rule triggered")
    actions.get("mail", "mail:smtp:gmail").sendMail("example@example.com", "This is the subject", "This is the message")

When I switch the Test switch to ON then mail is being sent and it ends up in my mailbox.

(I’m using openHAB 2.5.0.M2)

Are you complaining about the openHAB documentation or the helper library documentation? And what do you mean by “optional importing options”?

Did you follow the instructions, and did the hello_world.py script run for you?

This usually means you have not properly setup your EXTRA_JAVA_OPTS.

To use the 1.x Mail Action in 2.4, you will need to install it and then import it with…

from core.actions import Mail

The 2.x Mail binding was introduced after 2.4, so you would need to upgrade to use it. The 1.x Mail Action was moved to legacy when it was released. If you upgrade and use the 2.x Mail binding, you would just use the actions object, as Marcel has illustrated.

You must not have the 1.x Mail action installed. The core.actions module provides all OH 1.x action addons, OH 2.x core actions, and then the list that you see in the module. OH 2.x addons are not included, since they are available without import through the default script scope.

I can tell I have a lot to learn about jython scripts. I really like the way you are able to define a rule the way you did. Would be lovely if there was a main place with documentation for it and get rid of the older documentation showing the much less intuitive ways.

I have a few questions. Does this only work with OH 2.5 or should all of this code also work in OH 2.4? Also, where do I get the mail binding? I don’t see it listed in the Paper UI addons list.

I don’t mean to complain. :slight_smile:

Well, I just mean a list of things that can be imported to allow additional functionality. If such documentation exists, I don’t yet know where to look for it.

I was following the instructions I found here:
https://www.openhab.org/docs/configuration/jsr223-jython.html

I was not aware of the other instructions. It looks like step 7 about core seems to be the main thing I was missing in the instructions I was following.

It’s the last link in the documentation you were following. The helper libraries simplify use of scripted automation.

I see where you mean. It was easy to overlook as an installation step on that page though. It is listed as a resource and not obvious that it may be useful as part of the installation process.

I was able to install the helper libraries and the hello world script works for me:

"""
This script uses a decorated cron rule that will generate logs every 10s and can be used to test your initial setup.
"""

from core.rules import rule
from core.triggers import when

@rule("Jython Hello World (cron decorators)", description="This is an example cron triggered rule using decorators", tags=["Test tag", "Hello World"])# description and tags are optional
@when("Time cron 0/10 * * * * ?")
def hello_world_cron_decorators(event):
    hello_world_cron_decorators.log.info("Hello World!")

I will try to see if I can get a mail script to work now. I probably still don’t have the required binding for it installed though. I only have the mail action binding installed. But this is a nice step forward. I like how much easier the rule creation is with this helper script.

This now works. Thank you for the help.

2 Likes

The helper libraries are unofficial and are not required to use scripted automation, so they are not part of the installation steps on the OH site. They do make it a lot easier to use though.

The docs are always evolving, and the OH docs are due for an update.

1 Like

Perhaps @BigRedBrent could assist with that. :wink:

I doubt it… tabs are now available in the official docs, so I need to get back to… [WIP] NGRE/JSR223 Documentation refactoring

I do not want to come off as ungrateful. I usually try for several days if not weeks to figure out how to do things myself before asking for help. Usually I can stumble upon someone who has already asked for the help in the past.

And I greatly appreciate any and all documentation that has already been done. If I knew more about the topics I would gladly assist in improvements. But I am still very much a beginner in many things and can only help with the few things that I have figured out how to do myself.

I try to document things that I have learned and post them when I think others may benefit from something I had struggled with.

And thank you all very much for helping me with this.