/**
* simple sendmail .. lg kahn kahn@lgk.com
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*
* v 2.1 added desciprtive text and cleaned up debugging
* v 2.2 added hostname option and lookup ip if blank.
* v 2.3 added better checking for end of send to make sure it is closing cleanly
* v 2.4 add serial queueing so that a new connect waits while old finishes.. set timeout to 1 minute to wait. if email is not finished by
* then close connection and start new one. Also add state.lastCommand to follow the attribute as that seems more reliable.
* to this function telling me socket is closed but it obviously is not because responses are still asynchronously coming basck after!
* This "Stream is closed" messages seems to always come out after the quit command so it appears to be a status message not really an error
* v 2.4.2. try to workaround the check i had for the goodbye/bye message .. I was checkiong the value string on code 221 which was not a good
* approach as various servers can return differnent strings here. Unfortunately 221 just means remote server is closing so need to checkt
* that the message was sent and it is 221,
* v 2.4.3 true concurrency and queue using a thread safe data structure concurrentlinkedqueue and also mutex (thanks to erktrek)
* tested with up to 8 messages
* When one message finishes it checks the queue, and delivers any other remaining.. also schedules a rerun when busy and one is added to the queue.
* also serialize the setting and checking of the state.lastCommand as this is used to keep track of the async status of the commands
*
* v 2.5 changes were enough to signify new version. Found one bug in last one when reviewing code. a synchronize inside a synchronize on same semaphore.
* Did not seem to be causing issues so I assume the system is smart enough to avoid it but fixed anyway.
* v 2.5.1 mine got stuck in weird state and kept re-running with failure.. added an unschedule to fix it in certain cases and reset states. Also removed a function no longer called.
* Also reset state variable when it finds queue empty.
* v 2.5.2 change password input type to password from text
* v 2.5.3 auto turn off logging after 1/2 hour
* v 2.5.4 change formatting of date header
* v 2.5.5 change time formatting yet again.
* v 2.5.6 put extra lines in send to try to get around error in hubitat 2.2.5
* v 2.5.7 removed extra lines as bug is 2.2.5 and nothing to do with the lines.
* v 2.5.8 fixed email.. as summized version 2.2.5 telnet is stripping of extra lf or cr that are needed for email
* v 2.6 played with carriage return line feeds to get message back on first line..
* v 3.0 after recent release hubitat seems much slower getting the initial connect to the telnet port and therefore messages are stacking up .
* for this reason instead of queuing and trying 30 seconds later I have added a random component so it will queue and try 30 + 1-60 secs later.
* v 3.1 add desc. logging option default is on.. only a few lines of info come out when debugging is off. One for each email and a couple of others if queued up.
* this turns all that off.
* NOte: just noticed that if you send a bunch of message to the queue and also at the same time to another instance of the driver (ie another notification device) the queue
* is not distince. Meaining that all run in one process/thread.. The assumption is that each would be independent. Not the case . So the wrong device can get a message sent but it is rare.
* will look at somehow appending the device id to the queue and ignoring those not for you, but that is a big change .
* v 3.2 only one of the /r/n was needed before the body.. m
* v 3.3 got mms working from AT&T yeah.. so that we now can get all the msgs in one thread instead of the random number.
*
* V 3.4
* very very complicated. Spend about 6 hours on it.. here are my findings:
* 1. the date header must be there and in a specific format. It is so picky time zone must be in -0500 etc format not EST.
* 2. all FROM and TO emails must be in the form kahn@lgk.com . It automatically constructs this so don't enter them that way.
* 3. there must be headers for Message-ID , also enclosed in <>, MIME-Version, Content-Type, and Content-Transfer-Encoding.
* If any of these are missing or wrong the mms doesn't work from AT&T and you get an error email back.
* This thing is so damn picky and there is no documentaton on it whatsoever.
* Send some Beers my way.. What a pain the Ass Hopefully in works for everyone on your existing servers. If not let me know!
* It was also complicated to generate the unique message id. GetHubUuid() did not work.
* It works without a unique id, but I tried to generate one anyway. It uses a random UUID from a javascript function
* concatenated with the number of secs since midnight 1972 etc.
*
* v 3.5 Some email servers did not like the "email" format, so trying just in the recpt to and from headers.
*
* v 3.5.1 as someone pointed out the character map on hubitat is utf-8 not ascii so some special characters in emails were not being displayed correctly.
* v 3.6 noticed while i was having internet problems that the app kept spawning off retrying forever.. Notice the 2 attempts was not working.
* fixed it so it gives up after two failed attemps. also unchedules all pending and resets and tries again.
* v 4. add optional ehlo for servers that require it. Also need to handle the additional processing of EHLO informational messages coming back.
* v 4.01 bug gound with two typos with misspelling of lastCommand. Fix brought to light corresponding missing 250 checks.
* v 4 remove quit and close telnet coming out just for desc logging. Remove extaneous character at end of strings.
*
* Total rewrite here to scale much better for concurrenty!
* I create child devices (default is 5) but if you want more it is configurable.. Each child runs all its own data and can run totally concurrent with each other.
*
* Prior with the queuing it still sometimes would loose a message if two came in at exactly the right time. Even protected with semaphores the state variables could step on each other.
* This should never happend now. This also should scale really well say if you want to be able to send 50 concurrent messages very quickly you should be able to do that.
*
* There is also a new command called testConcurrancy which will start up a test email in each of your child simultaneously.
* also, implemented the Send message as a call to deviceNotification
* new parent.. instead of queing.. create 5 child devices and an array/map of them and current message being processed and status.
* when a new message comes in go through the list.. and find an available child and pass the message to it to process. mark it as being processed and
* clean up any that havent finished (ie mark free) in the given time out... default 2 minutes.
*
* Not released to hubitat package manager yet but put out there in my git hub.. you will need to install both LGK SendMail V3 and SendMailV3 child.
*
*
* 4.1 slight change to make children components of the parent so that only way to delete is through parent because if you deleted child directly it would screw up the app when it tries to pass
* a message to it. Also calculated friendly child name based on parent name.
* 4.2 added range to protect concurrent children.. added failure sensing for initial connect. added code to provide version to children.
*
*
* 4.3 ignore looking at status of completed when going through elements.
* V 4.5 add configurable timeout and retries .
* here and remove queuing and retry from the child process. add mutex and sempaphores around state variables in this driver function.
* remove mutex in child function.. Leave semaphore around lastCommand for now, although not sure it is needed.
* 4.51 fix bug with authentication and requires ehlo passed to child. (typos)
*
* v 4.6 clean up logging and missed debug on check.
* 4.7 tweek to double check child is not null in case cleanup is called way after a failed messages is left in queue.
*
* v 4.8 thanks to recommendations from mingaldrichgan Ming Aldrich-Gan
* support multiple emails in the to address.
* Add support for multiple recipients in "To", separated with commas, e.g. "abc@def.xyz, ghi@jkl.xyz"
* Each recipient is sent to the SMTP server on a separate "RCPT TO" line. I had to rewrite his
* recommended code changes using a different approach however as they were not working correctly in my tests.
*
* v 4.81 changes screwed up the subject and was mismatch between to and recpt to so total rewrite of new features.
* v 4.9 1/2023
* new changes to be able to modify/replace the From, to , subject or add a cc header
* the syntax is rh-Header: value,
* for instance to replace the subject form the hardcoded subject in your configurtion would be: rh-Subject: New Subject, Remainder of the message
* There must be a comma after each replacment header directive.
*
* same for to rh-To:, From is rh-From,
* to add a CC header, it is rh-CC: email@email.com etc.
*
* Notes: if you had a list of multiple to address in the configure only one can be in the new replacment header so that would override the entire list.
* other notes, order is important if you want to replace all headers (hence the rh-headername) you need to put them in this order:
* rh-From, rh-T0, rh-Subject, rh-CC .
* You dont need them all, but if any are there the must be in that order as that is the order they are processed.
* Otherwise the will be left in as part of your actual message.
*
* 4.91 added option for the subject header to be rh-Subject: or just Subject: to be consistent with ritchierich code base so you have
* have one notification send through both implementations.
* v 4.92
the original header replacement above still works
* but added an alternative message based on ritchierich pseudo xml at the start of the message
ie
{header: value, header: value}, this is the message
or
{header: value, header: value. Message: this is the message}
both work.
Legal header values for replacement are: Subject: From: To: CC: Message:
order is not important.
example:
{Subject: new subject, CC:kahn-zzspam@lgk.com, Message:newmessage here,To: kahn-saved@lgk.com, From: kahn@lgk.com}, this is a test
or
{Subject: new subject, CC:kahn-zzspam@lgk.com, Message:newmessage here,To: kahn-saved@lgk.com, From: kahn@lgk.com}
* 2/8/23 v 4.93 skip initial 220- as well as 250- which was already in place.
* 6/24 v 4.94 add desclog or debug check so single sent message doesnt come out unless one or the other or both are enabled.
*/
attribute "lastCommand", "string"
attribute "myHostName", "string"
import java.util.ArrayList;
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
import groovy.transform.Field
@Field static java.util.concurrent.Semaphore mutex = new java.util.concurrent.Semaphore(1)
@Field static java.util.concurrent.Semaphore status_mutex = new java.util.concurrent.Semaphore(1)
@Field static java.util.concurrent.Semaphore messageStateMutex = new java.util.concurrent.Semaphore(1)
@Field static java.util.ArrayList