Problem with sending email in javascript

I have searched but I can’t find an answer to what seems to be a very simple question: What is the correct script for sending an email from a rule using javascript. I have a script that works with Rules DSL but I’m trying to set up a timer with it and I think I need javascript for that. This is what I have that’s not working:

val mailActions = getActions(“mail”,“mail:smtp:be93f84a0f”) mailActions.sendHtmlMail(“me@myemail.com”, “Java Email”, “This is a java email test”)

I send a mail on every last day of the month with my smart meter status like this:

rule “Mail Smart Meter”
when
Time cron “0 0 17 L * ?”
then
val mailActions = getActions(“mail”, “mail:smtp:eee7c3eb4e”)
val text = new StringBuilder()
text.append(“Some text”)
text.append("\r\n")
text.append(“some additional text”)
text.append(String.format("%.0f",(SmartMeter_Energy.state as Number).floatValue))
mailActions.sendMail(“name@provider.com”, “State”, text.toString())
end

I had a look at the documentation and think it should work with sendHtmlMail also

getActions doesn’t exist in the javascript rules. You have to use one of the scriptExtention objects in this case the action object. Try actions.get(“mail”,“mail:smtp:be93f84a0f”) instead.

1 Like

Still not working. This is what I did:

val mailActions = actions.get(“mail”,“mail:smtp:be93f84a0f”) mailActions.sendHtmlMail("me@myemail", “Java Email”, “This is a java email test”

Logs:

val mailActions = actions.get(“mail”,“mail:smtp:be93f84a0f”) mailActions.sendHtmlMail("me@myemail", “Java Email”, “This is a java email test”

    ^ in <eval> at line number 1 at column number 4

Following works for me in OH3 JS rules:

var Actions = Java.type("org.openhab.core.model.script.actions.Things");
var mailActions = Actions.getActions("mail","mail:smtp:XXXXXXXX");
mailActions.sendMail("XXXXXX@YYYYYYY.com", subject, text);

Br,
Stefan

1 Like

Thanks konfetti, that gave me another error but I figured it out. The subject and text need the quote marks around them like this:

var Actions = Java.type("org.openhab.core.model.script.actions.Things");
var mailActions = Actions.getActions("mail","mail:smtp:be93f84a0f");
mailActions.sendMail("me@myemail.com", "subject", "text");

And for people like me who have a hard time with code, note that you can’t enter quote marks into text in a document & then paste it into a code window. Same key on the keyboard but the quote marks from the document are the curly ones instead of the straight ones that you need. Entering them into the script window works.

2 Likes