The Email Adapter
Learn more about the i4connected Email Adapter used to provide a way for physical devices to send alarms using the i4connected Event flow.
Unlike the other i4connected Adapters, the purpose of the Email Adapter is to parse emails that arrive at a specific mailbox and, based on the contents of these emails, to perform operations on alarms (raise, close, acknowledge) that are associated to devices and sites.
The parsing of the email is done using a script, representing the body of a C# function, that is configured for an email parser device, responsible for a specific email format, using protocols like IMAP, POP3, and Exchange.
The handling flow of the Email Adapter is based on a set of inbound and outbound operations, as follows:
The i4connected Email Adapter connects to the configured Email account and reads the received Emails.
The i4connected Email parser Device validates all the received Emails and consequently generates i4connected Events.
The Email parser Device has the ability to match Email contents with a set of optional parser filters (Sender Name Pattern, Sender Address Pattern, Recipient Name Pattern, Recipient Address Pattern, Subject Pattern, and Body Pattern). Using the filters ensures that only a subset of the emails will be parsed by a certain Email parser Device.
Depending on the matching process results, several outcomes can be distinguished.
If the matching process is successful, the Email is further on handled by the dedicated parsing script. The dedicated script will return all the needed information for generating events based on the parsed email. An important piece of information that should be parsed is the target device name. When the target device does not exist in the i4connected system, it will be created. As a final result, an Event is generated, having the Event source set to the target device.
The Extra Information area in the Event Occurrence details panel shows the Email metadata, such as Sender name and address, Recipient(s) name and address, Email subject, email body, and other useful information.
Note
The name of the target device is generated on basis of the script defined rule, which by default is "{siteName} - {deviceName}".
If the matching process is successful, but the parsed result does not contain all the needed information, to generate the event (e.g. Site name is missing), an Event is generated, having the Event source set to the parser device.
The user can easily identify the Event mismatch reason, by opening the Event occurrence in detailed view mode and checking the Extra Information area. The list below consists of all the potential mismatch reasons that can occur for an event having the name "The email occurrences could not be parsed":
"Missing script error."
"Script returned null."
"Script didn't return any alarm."
"Device name not found in the email."
"Alarm name not found in the email."
"Cannot create device without a valid site name."
"Site not found in the system."
"Error creating device '<parsed device name>'."
"Target device not found in the system."
"Target device is not active."
"Unexpected error."
and other exceptions related to Email contents validated against the parsing script.
If the matching process fails, meaning that no Email parser Device was configured with some patterns to match the email data, an Event is generated, having the Event source set to the Email Adapter communicating with the mailbox. The name of the generated event is "The format of the email was not recognized" and the additional information in the event metadata will contain the specific reason "There was no email adapter device configured to match the received email."
Warning
Spam emails will also be picked up by the i4connected Email Adapter and, most probably, there will be no email parser devices configured to handle such emails, so this event will be generated.
If an email without a body is received, an Event is generated, having the Event source set to the Email Adapter communicating with the mailbox. The name of the generated event is "The format of the email was not recognized" and the additional information in the event metadata will contain the specific reason "The email does not have a text body."
Email adapter connection
Check out this article and learn how to establish the connection between your mailbox and i4connected, by means of Email adapters.
The connection between the i4connected server and an Email server, is established by means of an Email adapter.
The list of already available Email adapters can be accessed by all the users having at least the View adapters permission enabled, by clicking the Email adapter name selector, in the Add / Edit Email Device panel.
In this view, all the already configured Email adapters are listed. The user can select an Adapter from the list and apply it to the Email parser device, update them, or remove them.
Note
Only users having the Manage adapters permission enabled can add and edit Adapters.
Additionally, the user can click the Add toolbar button to start configuring a new Email server
The Add email server panel features the following settings:
Name - specifies the name of the Email server.
Description - the user-friendly description of the Email adapter.
Poll interval(ms) - the data synchronization time interval, expressed in milliseconds (the default is 60000 – 1 minute).
Max messages - set the number of messages to read per polling cycle.
Site time zone metadata field - the name of the Site metadata, representing the time zone of the respective site.
If no Site time zone metadata is defined or if the defined one is not found, the Adapter time zone will be, by default, parsed.
Note
The Site time zone metadata needs to be defined by the system administrator, using the "Enumeration" type when adding the Custom field definition.
The list of enumeration values will be represented by a list of all valid time zones, available in the i4connected database.
For more details about the management of Custom field definitions, please also visit the dedicated article here. Further on, the management of Site metadata is described in this article here.
Error Event type - allows the user with the possibility to set the Event type, for the generated alarms. The Event type can be selected by clicking the dedicated selector. The list of Event types will be opened alongside, allowing the user to choose the desired Event type.
Note
By defining the Error Alarm type, the user can easily identify the generated online alarms and historical alarms, in the dedicated panels, by applying the respective filter.
For more details on the events filtering option, please also visit the dedicated article here.
Protocol - sets the communication protocol, allowing the user to choose from the following drop-down list items:
POP3 - The Post Office Protocol 3 is a standard protocol for receiving e-mails on a single device.
If the POP3 protocol is selected, the user is required to fill in the following account settings:
User name - specifies the user name of the POP3 Email server account.
Password - specifies the password used to access the POP3 Email server account.
Host - specifies the Email hosting service in which the email messages and associated files are stored on the server (e.g. pop.gmail.com).
Port - specifies the communication port of the POP3 Email server account (e.g. 995, when using SSL)
Use SSL - when set to true, the secure socket layer will be enabled (recommended).
IMAP - The Internet Message Access Protocol (IMAP) is a mail protocol used for accessing emails on a remote web server from a local client.
If the IMAP protocol is selected, the user is required to fill in the following account settings:
User name - specifies the user name of the IMAP Email server account.
Password - specifies the password used to access the IMAP Email server account.
Host - specifies the Email hosting service in which the email messages and associated files are stored on the server (e.g. imap.gmail.com).
Port - specifies the communication port of the IMAP Email server account (e.g. 993, when using SSL)
Use SSL - when set to true, the secure socket layer will be enabled (recommended).
Exchange - Microsoft Exchange, also known as Microsoft Exchange Server, is a type of account that can be added to an Email application.
Note
Exchange Web Services can be enabled and accessed using the OAuth authentication service provided by Azure Active Directory.
For more details on how to authenticate an EWS application, using OAuth please also visit this article here.
When selected as a communication protocol for the i4connected Email Adapter, the user is required to fill in the following settings:
Exchange App Id - specifies the OAuth application ID issued by Azure Active Directory.
Exchange Tenant Id - specifies the identification number of the application tenant.
Exchange Client Secret - specifies the application secret attributed to the OAuth application at the app registration step.
Exchange Url - The URL of the application, where authentication responses can be sent and received by the app.
Exchange Mail Box - the address of the target Email account.
Select owner - the name of the Adapter owner.
By clicking on the owner selector, the Select Users panel is opened allowing the user to chose the Adapter's owner.
Important
When adding a new Adapter the creator user is by default set as Adapter's owner. However, the owner can be changed after the Adapter was saved, by all users having at least the Manage adapters permission enabled.
Time zone - The time zone used by the new Email Adapter. By default, the Time zone is predefined for the currently logged-in user.
Note
By default, the generated Email alarms consider the Time zone selected at this field if no Site time zone metadata field is defined.
Trace Level - trace levels determine which events the trace provider generates. The user can select the desired trace level from a drop-down list where the following predefined values are available: Trace, Debug, Info, Warn, Error, Fatal, and Off.
Enabled / Disabled toggle button - If the setting is turned on, the Adapter is enabled and functional.
Email Alarm Script
Check out this article and learn more details about the Email Alarm scripts and how you can manage them for the Email Adapter.
As indicated, the core functionality when processing Email data, is the Email Alarm Script. Emails that have successfully passed the matching process, enforced by the parser filters are sent to the Alarm Script, selected by the user in the Add / Edit Device panel.
By clicking the Script selector, the Email Alarm scrips panel is opened, displaying all the existing scripts.
Note
The Email Alarm scripts list is accessible to all users having at least the Manage devices permission enabled.
By default, the Email Alarm scripts list is populated with eight script snippets, that the user can apply as they are, or customize them.
The default script snippets are:
Advitornic
Carel
Carel2
Danfoss
Dixell
Dixell2
Eliwell
Wurm
Users having higher authority permissions can also manage Email Alarm scripts, as follows:
Note
The Email Alarm scripts can be managed by all users having at least the Manage email event scripts permission enabled.
Editing and testing scripts
Check out this article and learn how to edit and test the Email adapter scripts, along with all details about the Script tab, the Test tab, the Results tab, and the Log messages tab.
Users having the Manage email event scripts permission enabled can open a listed script in edit mode, by clicking the Edit button.
The Edit Alarm Email script panel is structured into multiple tabs, where the user can write the script, test it, check the obtained results, and read log messages, as follows:
The Script tab
When opening the Edit Alarm Email Script panel, the Script tab is by default opened.
In this view, the fully customizable email script snippet is displayed, written in C# programming language.
Script - the script snippet acting as an email parser.
Tip
Unlike the Event script list expressions, which can also use simple online calculations, the Alarm Email script is based on a multi-line C# structure, enclosed between curly brackets {} and requiring a return function.
The "return" statement terminates the execution of the script and determines the generation of event occurrences, log messages, etc.
Even though C# is a high-level language, it is relatively easy to read. However, when it comes to editing the default Email script snippets, it is recommended that the user has, at least, basic programming knowledge.
For more details about the email script parameters and parsing helpers, please visit the dedicated article, here.
Description - the script description that will be displayed in all its applicable contexts.
In order to preserve any changes done in this tab, the user is required to click the Save button at the bottom of the panel.
The Test Script tab
The Test Script tab allows the user to check the script against a simulated email by providing the email elements Sender Name, Sender Address, Recipient Name, Recipient Address, and Subject.
In this view, the user can insert either a Text body or an Html body. Both fields allow the user with the possibility to simulate the emailing process, by clicking the Test button .
The simulation process is initiated in the background and the test outcome is displayed under the Results tab, which is automatically opened displaying more details about the operation.
The Results tab
The Results tab is usually opened automatically after triggering a test, under the Script Test tab.
In this view, the content of the simulated Alarm is displayed, allowing the user to see how the final result will look like or if the script was correctly configured.
Note
The Results tab provides the user with information only when it is opened after triggering a script test.
By clicking the Show object button, the View Metadata panel is opened, allowing the user to read more information about the simulated alarm metadata.
In case there are issues with the script, the Results tab provides the user with more information about the failure reason.
The Log Messages tab
The purpose of the Log Messages tab is to provide the user with additional support to validate the Email script snippet. It serves as a debug console, allowing the user to add messages in order to help creating a valid script.
The Log Messages tab is always available, in the Edit Alarm Email script panel, but the user can freely decide when to use it, by adding or removing script lines that output log messaged.
Deleting redundant scripts
Check out this article and learn how to delete redundant scripts, when working with the Email Adapter functionality.
The Edit Alarm Email Script panel provides the user with the possibility to remove a script, by clicking the Delete toolbar button. In the Delete snippet panel, the user is requested to manually fill in the deletion confirmation code. To proceed with the deletion operation the user can click the Delete button.
Adding new scripts
Check out this article and learn more details about the Email adapters scripts and how to add new ones, properly configured.
Users having the Manage email event scripts permission enabled can create new Alarm Email scripts, by clicking the Add toolbar button available in the Email Alarm scripts.
The Add Alarm Email Script panel is also split up into four tabs, each being dedicated to a specific task:
Under the Script tab, the user can start writing the script that will be used to parse Emails and generated Alarms.
Warning
As already indicated, the Script field expects a C# type script.
To preserve the written script, the user needs to click the Save button located at the bottom of the panel.
The Test Script tab is dedicated to validating the written script, against a set of parser filters.
The Results tab displays the tested results, providing the user with the chance to check if the script works as expected, before saving and using it.
The Log Messages tab displays the logs registered during the script testing phase.
Email adapter scripting
Check out this article and learn everything that you need to know about the email adapter scripting parameters and the involved parsing helpers.
Email script
The Email Adapter script is responsible for a specific email format. The script represents the body of a C# function. Since the function signature is not visible in the script editor, provided by the i4connected interface, this article will describe:
the input parameters:
email
the expected result, of type:
AlarmEmailScriptResult
public AlarmEmailScriptResult ParseOccurrences(EmailEntry email)
Parameters
The "email" is the only parameter of the parsing function and it is of type "EmailEntry". It contains all the fields of the received email:
Parameter | Type | Description |
---|---|---|
SenderName | String | This is the name of the email sender, as displayed in any email client. It is not always available. |
SenderAddress | String | This is the email address of the sender. |
Subject | String | This is the email subject. |
TextBody | String | This is the text format of the email body. The availability of this field depends on the way the sender wrote (sent) the email. Some emails may contain only a text body, only an HTML body, or both. The script creator should know what is the body format that contains the necessary information for creating alarms and use the appropriate field. |
HtmlBody | String | This is the HTML format of the email body. The availability of this field depends on the way the sender wrote (sent) the email. Some emails may contain only a text body, only an HTML body, or both. The script creator should know what is the body format that contains the necessary information for creating alarms and use the appropriate field. When the HTML body is needed, an HTML to text converter is provided in a helper function (ParsingHelper.ConvertHtmlToText), to make it easier to parse this type of email body. The helper functions will be described later in this document. |
Recipients | List<EmailRecipientEntry> | This is the list of recipients of the email. Each element in the list is of type "EmailRecipientList" and will have the following fields:
|
Returns
An object of type "AlarmEmailScriptResult":
Parameter | Type | Description |
---|---|---|
LogMessages | String | This string array will contain log messages added by the script to enable easier debugging. These messages will be displayed in the script editing panel. The script creator is free to add as many messages as needed and format them in a way that helps to identify possible issues. |
Occurrences | OccurenceDetails | This array contains the details of the alarms that will be raised, as a result of the email parsing. Each entry in this array will trigger at least one alarm operation in the i4connected system (raise, close, acknowledge). If this array is null or empty, an error alarm will be raised. Each element is of type OccurrenceDetails and has the following fields:
|
Parsing Helpers
To make it easier to parse the emails, a static class is provided, ParsingHelper, which contains several helper methods for dealing with the email contents. All these methods are static, meaning they are invoked like this ParsingHelper.<name_of_method>(params).
For example: ParsingHelper.ConvertHtmlToText(html, false).
Methods
string ConvertHtmlToText(string html, bool tdToTab = false)
Description - Converts an HTML formatted text into plain text.
Parameters
HTML (String) - This is the HTML text to be converted into plain text. Usually, this will be the htmlBody field from the email parameter of the script.
tdToTab (boolean) - This flag decides whether the TD elements will be converted to tabs or newlines in the resulted text. The default is false, meaning that this parameter can be omitted, and the TD elements will be converted to newlines.
Returns
string - the converted text
string ParseField(string line, string startSeparator, string endSeparator)
Description - Extracts a substring from a given text, based on the provided start and end separators.
Parameters
line (String) - the line of text from where the desired substring will be extracted.
startSeparator (String) - the separator that represents the starting indicator of the text. If the start separator is null or empty, the result will include everything from the start of the input text (line) until the end separator.
endSeparator (String) - the separator that represents the ending indicator of the text. If the end separator is null or empty, the result will include everything from the start separator until the end of the input text (line).
Returns
string - The part of the input string (line) contained between the start and end separators.
string[] SplitIntoLines(string input, bool returnEmptyLines = false)
Description - Splits the given input string into lines.
Parameters
input (String) - the input which will be split.
returnEmptyLines (Boolean) - this flag decides whether any resulting empty lines are returned in the result. The default is false, meaning that this parameter can be omitted, and empty lines will not be a part of the result.
Returns
string - a collection of lines resulted from splitting the input string.
List<string[]> SplitIntoBlocks(string input, int newLineCountToUseForSplitting, bool returnEmptyLines = false)
Description - Splits the given input into blocks of lines, based on the specified number of new lines between blocks.
Parameters
input (string) - t input string which will be split.
newLineCountToUseForSplitting (Int) - the number of the new lines that should be used for splitting the text into blocks.
returnEmptyLines (Boolean) - this flag decides whether any resulting empty lines are returned in the result. The default is false, meaning that this parameter can be omitted, and empty lines will not be a part of the result.
Returns
List<string[]> - a collection of blocks, each one consisting of lines of text, resulted from splitting the input string.
Email Events handling
Check out this article and learn more details about the handling of i4connected alarms generated by the Email Adapter.
Events generated by the Email script parser can be managed in the Online Alarms panel, providing the user with the same functions available for all i4connected Events, such as close, acknowledge, take ownership, assign ownership, prioritize and comment.
Tip
For more details about Online Alarms management, please also visit the dedicated article here.
As described at the beginning of this article, the Email account configured for the Email Adapter is periodically checked for new Emails. Each new Email is consequently matched with a set of filter patterns. Depending on the results of this matching process, an Event is generated and made available in the Online Alarms panel.
Listed Email Events can be opened in detailed view mode, by all users having at least the View events permission enabled.
Tip
For more details about the Event Occurrences panel, please also visit the dedicated article here.
When opening an Email Event occurrence in detailed view mode, besides the event sources (Device / Adapter / Site) the user can also access the Email Alarm Scripts list, by clicking the Script selector. Users having the Manage event scripts permission enabled can edit and test Email scripts, as described by the dedicated article.
The Extra Information area of Email Event occurrences provides the user with more details about the event.
If the event occurred as a result of a parsing error, the user can get information about the reason for failure under the Extra Information area.
Tip
For more details about possible mismatch and failure reasons, please also read the overview article.