Introduction
This article describes how to send email notifications using the SendGrid API and Displayr...
...based on a table.
Requirements
- A Displayr document with an output showing the data points you wish to show in your email. In this example, we will be pulling the highest and lowest brands.
- A SendGrid account with a valid API key found in SendGrid under Settings > API Keys > Create API Key > Full Access > Create & View.
Please note this requires the Data Stories module or a Displayr license.
Method - Create the email content
1. Select Calculation > Custom code.
2. Paste the below into the R CODE section of the output:
input.data = round(nps.table, 1)
max.value = max(input.data)
max.label = names(input.data)[which(input.data == max.value)]
min.value = min(input.data)
min.label = names(input.data)[which(input.data == min.value)]
message.body = paste0("Here are the latest results from your NPS survey.",
"\\n\\nThe highest NPS score this month was ", max.value, " for ", max.label,
", while the lowest NPS score this month was ", min.value, " for ", min.label, ".")
In this example, we are pulling out the brands with the highest and lowest NPS scores from a table called nps.table. The message.body pastes together these labels and values with specified text to form our email content. Note, the "//n" adds a line break within the text.
Method - Create the Workflow
1. Add the below R code after the email content code:
require(httr)
require(jsonlite)
require(flipTime)
# Frequency
UpdateEvery(24, "hours", options = "snapshot")
# Email parameters
to.email = "recipient@domain.com"
from.email = "sender@domain.com"
subject = "Test Email"
msg = sprintf('{"personalizations":
[{"to": [{"email": "%s"}]}],
"from": {"email": "%s"},
"subject": "%s",
"content": [{"type": "text/plain",
"value": "%s"}]}', to.email, from.email, subject, message.body)
# API call
key = "your_api_key" #enter your API Key here
pp = POST("https://api.sendgrid.com/v3/mail/send",
body = msg,
config = add_headers("Authorization" = sprintf("Bearer %s", key),
"Content-Type" = "application/json"),
verbose())
Here, we first set the frequency for the update, and then define the email addresses, subject line, and type of email. The message body from the previous steps is also referenced here. Finally, we use the SendGrid API to send the email alert using the authentication API key.
2. OPTIONAL: You may need to wrap the API call in a basic if condition to better control when the alert should send if you have other automated actions being performed in your document.
3. OPTIONAL: If you wish to send HTML emails instead of plain text, change "content": [{"type": "text/plain",
to "content": [{"type": "text/html",
. This will then allow you to add HTML code to your message.body content to create, for example, bullet point lists and hyperlinks.
See Also
How to Import Data into Displayr