I haven’t posted anything in a while, as I have been working on another project which I am hoping to unveil very soon. In the meantime, I wanted to talk about K2 and Exchange. We all know that K2 can talk to Exchange, send emails and receive replies back in the form of SmartActions out of the box.

But what if we want to keep track of the emails sent from a K2 app? This gets a bit tricky. We could save the message in a database using a SmartObject event and then use the email event to send it. That’s an OK approach, but I think it could be done better, without needing two steps/events.

So let’s have a think about what I want the assembly to do:

  • Send an email
  • View the mailbox
  • View an email

We could modify the existing email event to do what I am suggesting below, but that would be a pain. We would need to do it every time we used the email event, and the person building the workflow would need to be able to write code. The approach I am going to go through lets anyone build a workflow that tracks the emails being sent without writing code. More importantly, every app will be able to see the emails it has sent out.

We are going to create an email endpoint assembly that lets a workflow send an email that references a primary key, SN, process instance ID or application type (see my framework post), and then view its mailbox by the same information.

Getting started

We will need the following:

  • Visual Studio 2015+
  • The Microsoft Exchange Web Services (EWS) URL
  • The Exchange version
  • A user account set up just for the K2 mailbox (I normally create a service account that just has a mailbox)
  • That user account’s email address
  • Microsoft.Exchange.Webservices.dll

Once we have the above, we can start building the new email endpoint assembly.

EWS code

To set up the connection to Exchange Server, it is important to identify which version of Exchange we are talking to.

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

Once we have created an instance of the Exchange service, we give it the Exchange web service URL.

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
service.Credentials = new WebCredentials("Username", "Password");

service.Url = new Uri("Web service");
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "Email Address");

We now have a connection to Exchange Server via its web service, and we can do a number of different things, such as:

  • Send an email
  • View mailbox contents, such as the inbox or sent items
  • View an email
  • Create meeting requests

We will look at the basic code for sending an email.

Sending an email

To send an email we create an instance of the EmailMessage object and pass in the ExchangeService object. Then we can use the properties and methods of EmailMessage. We can give our email a subject and a body, and decide whether to send a plain text or an HTML message.

EmailMessage email = new EmailMessage(service);
email.Subject = "Subject";
email.Body = new MessageBody(BodyType.HTML, Body);

To add recipients (To, Cc, Bcc) we just need the following code:

email.ToRecipients.Add("address");
email.CcRecipients.Add("address");
email.BccRecipients.Add("address");

If there is more than one email address for To, Cc or Bcc, we can simply loop through the addresses in the method parameter, like in the example below.

 if (To.Contains(";"))
 {
 String[] to = To.Split(';');
 foreach (var address in to)
 {
 email.ToRecipients.Add(address);
 }
 }
 else
 {
 email.ToRecipients.Add(To);
 }

To send the email, we call:

 email.SendAndSaveCopy();

Now we can send a basic email. So let’s look at how we can extend it to carry some additional properties that relate to the workflow it was sent from.

The EmailMessage object lets us add what are called extended properties, and they are really simple to create. The only thing to remember is that the GUID used to identify a property must be the same every time an email is sent, and the same when we retrieve the mailbox.

In this example I am going to bind the process instance ID to the email message. We will then be able to search the sent items and retrieve all the messages that relate to that process instance.

Creating extended properties

This is the most important part. Extended properties are what let us group emails by the process instance ID, business key and so on.

Create a GUID called ‘ProcessInstanceId’ and assign it a value.

Guid ProcessInstanceId_PropertySetId = Guid.Parse("fc0a27be-f463-472e-bea8-648e62d1d7dc")

We then define the extended property by giving it a name, in this case ‘ProcessInstanceId’, and setting its data type to String.

 ExtendedPropertyDefinition ProcessInstanceId_ExtendedPropertyDefinition = new ExtendedPropertyDefinition(ProcessInstanceId_PropertySetId, "ProcessInstanceId", MapiPropertyType.String);

With the property defined, we can populate the email with the process instance ID. In the code below I check whether ‘ProcessInstanceId’ is greater than 0 or not null. If so, the property gets the value of ‘ProcessInstanceId’; if not, it gets 0.

email.SetExtendedProperty(ProcessInstanceId_ExtendedPropertyDefinition, (ProcessInstanceId > 0 | ProcessInstanceId != null ? ProcessInstanceId : 0));

Now every email we send will contain the process instance ID. In the full ‘SendEmail’ method I have also added properties to hold:

  • The primary key of the main business data
  • ProcessTypeId (see my framework post)
  • The folio of the process instance
  • A MessageId, so we can identify each email

Here is the shape of that method, with one of the extended properties shown. The others follow exactly the same pattern.

public static string SendEmail(string Subject,string Body, string To, string Cc,string Bcc,int importance, string sn,string Folio, int? ProcessInstanceId, string ProcessTypeId, string BusinessKey)
 {
 string result = string.Empty;
 ExchangeService service = ConnectToExchange();
 try
 {
 if (To != null || To.Length != 0)
 {
 EmailMessage email = new EmailMessage(service);
 email.Subject = Subject;
 email.Body = new MessageBody(BodyType.HTML, Body);
Guid SN_PropertySetId = Guid.Parse("fc0a27be-f463-472e-bea8-648e62d1d7dc");
 ExtendedPropertyDefinition SN_ExtendedPropertyDefinition = new ExtendedPropertyDefinition(SN_PropertySetId, "SN", MapiPropertyType.String);
 email.SetExtendedProperty(SN_ExtendedPropertyDefinition, (!String.IsNullOrEmpty(sn) ? sn : "0_0"));
 // ... Folio, ProcessInstanceId, BusinessKey, ProcessTypeId and MessageId are set the same way
 // ... To, Cc and Bcc recipients and importance are added here
email.SendAndSaveCopy();
result = email.Id.ToString();
 }
 }
 catch(Exception ex)
 {
 result = "Error: " + ex.Message.ToString();
 }
 return result;
 }

The full listing is in the original post.

Retrieving an Exchange mailbox

Now that we can send emails with K2-related data, we need to be able to retrieve them, so we can view them in a SmartForm.

The mailbox method defines the same extended properties (with the same GUIDs), adds them to the view’s property set, and then reads them back off each item it finds in either the sent items or the inbox.

public static List<EmailBox> GetMailBox(string MailBoxType,int PageSize)
 {
 ItemView view = new ItemView(PageSize);
 List<EmailBox> list = new List<EmailBox>();
 // ... the six ExtendedPropertyDefinitions are declared here, as in SendEmail
ExchangeService service = ConnectToExchange();
 view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, SN_ExtendedPropertyDefinition, Folio_ExtendedPropertyDefinition, ProcessInstanceId_ExtendedPropertyDefinition, BusinessKey_ExtendedPropertyDefinition, ProcessTypeId_ExtendedPropertyDefinition, MessageId_ExtendedPropertyDefinition);
FindItemsResults<Item> findResults = service.FindItems((MailBoxType == "Sent" ? WellKnownFolderName.SentItems : WellKnownFolderName.Inbox), view);
 foreach(Item email in findResults.Items)
 {
 Item mail = Item.Bind(service, email.Id);
 list.Add(new EmailBox
 {
 MailBoxType = MailBoxType,
 Subject = mail.Subject,
 Body = mail.Body,
 // ... the other standard email fields
 SN = (email.ExtendedProperties.Count > 0 ? email.ExtendedProperties[0].Value.ToString():string.Empty),
 Folio = (email.ExtendedProperties.Count > 0 ? email.ExtendedProperties[1].Value.ToString(): string.Empty),
 ProcessInstanceId = (email.ExtendedProperties.Count > 0 ? email.ExtendedProperties[2].Value.ToString(): string.Empty),
 BusinessKey = (email.ExtendedProperties.Count > 0 ? email.ExtendedProperties[3].Value.ToString(): string.Empty),
 ProcessTypeId = (email.ExtendedProperties.Count > 0 ? email.ExtendedProperties[4].Value.ToString(): string.Empty),
 MessageId = (email.ExtendedProperties.Count > 0 ? email.ExtendedProperties[5].Value.ToString(): string.Empty)
});
}
 return list;
}

Retrieving an email

Now that we can get a list of emails from a mailbox, we also need to be able to retrieve a single email. We bind to the item by its ID and read the same fields and extended properties.

public static EmailBox GetEmail(string Id)
 {
 EmailBox email = new EmailBox();
 ExchangeService service = ConnectToExchange();
try
 {
 Item mail = Item.Bind(service, (ItemId)Id);
 {
 email.Subject = mail.Subject;
 email.Body = mail.Body;
 // ... the other standard fields and the extended properties, as in GetMailBox
}
}
 catch(Exception ex)
 { }
 return email;
 }

With these methods to send an email, retrieve a mailbox and retrieve an email, we can register the library as an endpoint assembly.

We could extend this to add attachments, and we could also look at calendar meeting requests and extend their properties in the same way.

We can then build a SmartObject around it and use it in our workflows and SmartForms. To make the new email SmartObject even easier to use, we could wrap a SmartWizard around its methods.

The full solution was available to download from the original post.