Pre-process parameters

In this example, you will create a workflow that sends an email from an external mail server such as Gmail, rather than from Nintex Automation Cloud. The Gmail API requires parameters A piece of information passed to a third-party API during a request. to be sent as something other than JSON JavaScript Object Notation: a data format based on JavaScript that is commonly used for API request parameters and responses., so you will create a serverless function A service that allows you to run code without provisioning and managing a web serve to host it. Examples include Amazon Web Services and Microsoft Azure. to pre-process the parameters from Nintex Automation Cloud into the required format and pass them through to the API A programming interface that defines how software can be interacted with by other software..

The complete OpenAPI Specification A standard, language-agnostic description of RESTful APIs that can be read by both humans and machines. Formerly known as Swagger., serverless code and icon for this example are available here. You can test the example using our provided serverless functions*, or write your own.

Nintex Automation Cloud provides parameters to APIs as individual parameters. Some APIs require their parameters to be delivered in a different format, such as XML, or a complex JSON object. A serverless function can take the parameters from Nintex Automation Cloud and convert them into the format expected by the API, make the API call and pass back any returned data to Nintex Automation Cloud.

You then define your OpenAPI Specification to match your serverless function, and import it into Nintex Automation Cloud like any other Xtension A set of instructions for Nintex Automation Cloud to use third-party API functionality with Nintex workflows. An Xtension may include workflow actions, start events, forms or file control..

Create a test Google account

We strongly recommend using a test Google account to email from when testing this workflow, rather than a personal account. For security reasons, Google restricts access to the Gmail API, and you will need to remove these protections on the test account to test your workflow. This does not affect your Google developer account.

  1. Create a test Google account.
  2. Using the test account, join the Google group at this link: https://groups.google.com/forum/#!forum/risky-access-by-unreviewed-apps

Joining the group removes the protections that prevent unreviewed apps from accessing the Gmail API on this account. When you have finished testing this example, you can leave this group to restore those protections.

Create the serverless function

Step 1: Register for authentication

You must enable the Gmail API in your Google Developer account, and create the client ID and shared secret:

  1. If you do not already have a Google Developer Account, create a free account here.
  2. Click the following link to open the Google API console.
  3. Click Enable API and type Gmail in the search box.
  4. Click Enable.
  5. Click Credentials in the left hand navigation pane.
  6. Click Create credentials, and select OAuth client ID.
  7. Select Web application.
  8. Type Nintex Automation Cloud connector for Gmail in the Name field.
  9. Click Create.
  10. Record the Client ID and Client Secret somewhere secure. You will need these to import the Xtension into Nintex Automation Cloud.

Step 2: Examine the API

Examine the API documentation at the following link: https://developers.google.com/gmail/api/v1/reference/users/messages/send.

The API requires the email recipient list, subject and message body to be built as a single object.

Step 3: Build the code

Create a function in a language supported by your serverless function provider to convert the Nintex Automation Cloud parameters to the required format. In this example, we have written a Microsoft Azure serverless function in C#.


#r "Newtonsoft.Json"

using System;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Text;

private const string gmailMessageApiUrl = "https://www.googleapis.com/gmail/v1/users/me/messages/send";

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
  // Check the authorization header, BadRequest if it's not provided
  var authorizationHeader = req.Headers.FirstOrDefault( x => x.Key == "Authorization")
                            .Value?.FirstOrDefault();
  if(string.IsNullOrEmpty(authorizationHeader))
  {
    return req.CreateResponse(HttpStatusCode.BadRequest, 
                              "Authorization header missing or empty.");
  }

  // Read the request body
  dynamic data = await req.Content.ReadAsAsync<object>();

  // Let's create the email object payload. 
  var sb = new StringBuilder(1024);
  sb.Append($"To: {data.To}{Environment.NewLine}");
  sb.Append($"Cc: {data.Cc}{Environment.NewLine}");
  sb.Append($"Subject: {data.Subject}{Environment.NewLine}{Environment.NewLine}");
  sb.Append($"{data.Message}");

  // Create the raw payload by Base64 encoding our payload
  var raw = Convert.ToBase64String(Encoding.UTF8.GetBytes(sb.ToString()));

  // Build a json object expected by Gmail servers. "raw" property will contain our
  // Base64 encoded email object
  var requestBody = new JObject();
  requestBody.Add("raw", raw);

  // Send the request to the endpoint URL. 
  HttpClient client = new HttpClient();
  var request = new HttpRequestMessage(HttpMethod.Post, gmailMessageApiUrl);

  // Inject the OAuth2 token into the request
  request.Headers.Add("Authorization", authorizationHeader);
  request.Content = new StringContent(requestBody.ToString(), Encoding.UTF8, "application/json");

  return await client.SendAsync(request);
}

Create the Xtension

Build an OpenAPI Specification that provides the parameters required by your serverless function, and accepts its response:

Note: If additionalProperties is not defined for an object, it defaults to true, allowing workflow designers to add arbitrary properties to that object.


{
    "swagger": "2.0",
    "info": {
        "version": "1.0.0",
        "title": "Gmail Messages"
    },
    "host": "prdhlpsmpfncwus01.azurewebsites.net",
    "basePath": "/api",
    "schemes": [ "https" ],
    "produces": [ "application/json" ],
    "paths": {
        "/GmailSendEmail": {
            "post": {
                "tags": [ "Message" ],
                "summary": "Send Gmail Message",
                "description": "Send Gmail Message",
                "operationId": "sendMessage",
                "produces": [ "application/json" ],
                "parameters": [
                    {
                        "name": "request",
                        "description": "Message",
                        "in": "body",
                        "schema": {
                            "type": "object",
							"additionalProperties": false,
                            "properties": {
                                "To": {
                                    "type": "string",
                                    "description": "Recipient email address"
                                },
                                "Cc": {
                                    "type": "string",
                                    "description": "CC email address"
                                },
                                "Subject": {
                                    "type": "string",
                                    "description": "Email subject"
                                },
                                "Message": {
                                    "type": "string",
                                    "description": "Message to send"
                                }
                            }
                        },
                        "required": true
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    },
                    "default": {
                        "description": "Operation Failed"
                    }
                },
                "security": [
                    {
                        "gmailOauth2": [ "https://mail.google.com/" ]
                    }
                ]
            }
        }
    },
    "securityDefinitions": {
        "gmailOauth2": {
            "type": "oauth2",
            "flow": "accessCode",
            "authorizationUrl": "https://accounts.google.com/o/oauth2/v2/auth",
            "tokenUrl": "https://www.googleapis.com/oauth2/v4/token",
            "scopes": {
                "https://mail.google.com/": "access gmail"
            }
        }
    }
}

Create the workflow

Step 1: Add your Xtension

Import the OpenAPI Specification you created into Nintex Automation Cloud:

  1. Open your Nintex Automation Cloud tenancy.
  2. Click Xtensions in the dashboard to open the Xtensions page.
  3. Click  in the Private connector list.
  4. Click Choose a file. Navigate to the OpenAPI Specification on your computer.
  5. Wait for Nintex Automation Cloud to validate the file.
  6. Click Next.
  1. Nintex Automation Cloud detects the OAuth 2.0 security template.
  2. Type the Client ID in the Client ID field.
  3. Type the shared secret in the Client Secret field.
  4. Copy the Redirect URL: you will need to add this to your OAuth credentials in your Google Developer Console.
  5. Click Next.
  1. Edit the Name of the Xtension, which becomes the name of the action group in the Workflow designer.
  2. Edit the Description of the Xtension. This appears in the Private connector list in the Xtensions page.
  3. Select or upload an icon for the Xtension. This is displayed for each action or event in the Workflow designer.
  4. Click Publish.

Step 2: Authorize the redirect URL

The API will only accept requests that redirect to URLs that have already been authorised for the OAuth2 credentials. To authorise the redirect URL:

  1. Open the Credentials section of the Google Developer Console.
  2. Edit the OAuth2 credentials you created earlier.
  3. Paste the Redirect URL you copied into the Authorized redirect URIs field.
  4. Click Save.

Step 3: Create the workflow

The workflow will use a public web form to prompt the user for the recipient email addresses, subject and message to send. The workflow will check if the email recipient is internal to the company or not, and send internal emails from Nintex Automation Cloud, and external messages from the test Google account.

For more information on creating workflows, see the Workflow Designer.

To create the workflow:

  1. Click Create workflow in your Nintex Automation Cloud tenancy.
  2. Configure the Start event to be a Nintex - form with four text variables:
    • The To email recipient
    • The Cc email recipient
    • The email subject
    • The email body

    For more information on designing forms in Nintex Automation Cloud, see Design a form.

  3. Drag a Branch by condition action after the Start event.
    For more information, see Branch by condition.
  4. Configure the Branch by condition action to test whether the To variable contains your company email domain.
  5. Drag a Send Gmail Message action into the No branch.
  6. Connect the Send Gmail Message action to your test Google account
  7. Use the start variables for the four configuration fields.
  8. Drag a Send an email action into the Yes branch.
    For more information, see Send an email.
  9. Configure the Send an email action with the form fields.
  10. Click Test to test the workflow.
  11. Save or publish the workflow.

Tip:  If you want to troubleshoot an Xtension, select Development as the Assigned Use when you publish the workflow. Development workflows display more detailed error messages in their instance details. Republish your workflow as Production when you're ready to use it.

* The serverless function in this example is provided on an as-is basis for this demonstration only, and is not suitable for a production environment. Example serverless functions are not covered by the Nintex service level agreement.