<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/automatically-write-and-email-reports-with-r-sendgrid-displayr/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.displayr.com/automatically-write-email-reports-using-r-sendgrid-displayr/?utm_medium=Feed&utm_source=Syndication"> R – Displayr</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>This post explains how to use R to automatically write and send emails based on automatically computed analyses (yep, everything automated). This means that when analysis changes or is updated, the email body text changes as well. The email can then be automatically sent to clients based on a trigger event (e.g., only when results are interesting) or periodically. All of this is can be done by using R code in Displayr, as illustrated in this post.</p>
<hr>
<h2><span>The tools: R, Displayr, and SendGrid</span></h2>
<p>To automatically write and send email reports we need to have three tools:</p>
<ul>
<li>A programming language. If the analysis is non-trivial, R is usually the best way forward.</li>
<li>An app that can automatically run the analyses at specified times. I’ve used Displayr. Of course, if you have the time you can avoid this commercial product and set up your own servers. (Disclaimer, I work for Displayr.) You can read this post to see <a rel="nofollow" href="https://www.displayr.com/introduction-to-displayr-2-data/" target="_blank">how to get your data into Displayr</a> and <a rel="nofollow" href="https://app.displayr.com/SignUp" target="_blank">sign up to Displayr</a> here if you do not already have an account.</li>
<li>An app to actually send the emails. I’ve chosen an email delivery application called <a rel="nofollow" href="https://www.sendgrid.com/" target="_blank">SendGrid</a> because R can work with its API.</li>
</ul>
<hr>
<h2><span>Step 1: Set up the analysis to automatically update</span></h2>
<p>The first step is to perform the analysis. Presumably, you want to set this up so that you have a live feed of data with the analysis updating automatically. See <a rel="nofollow" href="https://www.displayr.com/automatic-updating/" target="_blank">Automatically Updating Data and Dashboards in Displayr</a> for more about this.</p>
<hr>
<h2><span>Step 2: Create a SendGrid account so you can send emails</span></h2>
<p>Go to the <a rel="nofollow" href="https://app.sendgrid.com/signup" target="_blank">Sendgrid account signup page</a> to create your account. Enter a username, password and email address and select the 30-day free trial option which allows you to send up to 40,000 emails. Click the <strong>Create Account</strong> button and then complete the additional fields on the next page (your role, company size, etc.) to complete the account setup process.</p>
<p><img sizes="(max-width: 300px) 100vw, 300px" src="https://i0.wp.com/www.displayr.com/wp-content/uploads/2017/08/sendgrid_account_setup2-300x255.png?resize=300%2C255&ssl=1" alt="sendgrid account setup" class="wp-image-2817" data-recalc-dims="1"></p>
<hr>
<h2><span>Step 3: Create a SendGrid API key</span></h2>
<p>Once your SendGrid account has been set up, you can now create a SendGrid API key. The API key is a code that will enable your own R code to ask SendGrid to send emails. From your SendGrid account dashboard:</p>
<p><img sizes="(max-width: 166px) 100vw, 166px" src="https://i2.wp.com/www.displayr.com/wp-content/uploads/2017/08/settings_apikey2-166x300.png?resize=166%2C300&ssl=1" alt="sendgrid settings" class="wp-image-2816" data-recalc-dims="1"></p>
<ol>
<li>Select<strong> Settings > API Keys</strong></li>
<li>Click the blue <strong>Create API Key</strong> button in the top right corner of your screen.</li>
<li>On the Create API Key screen, enter an API Key Name (for example, <span>Displayr_APIKey</span>).</li>
<li>Select the <strong>Full Access</strong> option.</li>
<li>Click the <strong>Create &amp; View</strong> button to generate and display the API Key.</li>
<li>Click on the displayed API key to copy it.</li>
<li>Paste the key into a text editor, and save it to a text file on your hard-drive for safe-keeping. Note that for security reasons, SendGrid will not display the API key again.<img sizes="(max-width: 1024px) 100vw, 1024px" src="https://i0.wp.com/www.displayr.com/wp-content/uploads/2017/08/sendgrid_apicreated-1-1024x476.png?w=450&ssl=1" alt="automatically write and email reports" class="wp-image-3088" data-recalc-dims="1"></li>
</ol>
<hr>
<h2><span>Step 4: Write the email body</span></h2>
<p>The next step to automatically write and email reports is to write the email body. The message text for the email needs a string, stored in Displayr in an <em>R Output. </em>To create an R output, open Displayr and select <strong>Insert > Analysis > R Output</strong>. You then type in completely standard R code, referring to the data in your Displayr document.</p>
<p>In the rest of this post, I assume that the R Output that contains the email content is called <span>body</span>.</p>
<p>For example, a simple document may contain a set of NPS scores for different brands, like those shown in the table below.</p>
<p><iframe src="https://embedded.azureedge.net/75668/231472/1e20eecc-2a01-4fc6-9dca-26a640ba43a3.html?v=28776-fcdfeecfd9-796853713" data-mce-fragment="1" width="214.11" height="411.7"></iframe></p>
<p>Using R, I can pull out the highest and lowest results from the table (which in this case are for Google and IBM), and I can construct the following rather messy-looking piece of text:</p>
<p><iframe src="https://embedded.azureedge.net/75668/231472/9af5f885-a8ac-4a38-b5a9-a158060f88dd.html?v=28776-fcdfeecfd91014599173" width="418" height="179.8846"></iframe></p>
<p>If you sign in to Displayr you can <a rel="nofollow" href="https://app.displayr.com/Try/Sending%20Automated%20Emails" target="_blank">look at the example code</a> that I used to build this message from the table above.</p>
<p>It may look messy now, but when the email is created, the <span>\n</span> tags will be converted into line breaks, and it will produce an email that looks like this:</p>
<p><img sizes="(max-width: 750px) 100vw, 750px" src="https://i1.wp.com/www.displayr.com/wp-content/uploads/2017/09/Plain-nps-email.png?w=450&ssl=1" alt="Automatically write and email reports" class="wp-image-3368" data-recalc-dims="1"></p>
<p>Additionally, you can include the URL of your published Displayr document in the message. To obtain the URL, first, export your document using <strong>Export > Web Page</strong>, and then copy and paste the URL of the resulting page.</p>
<hr>
<h2><span>Step 5: Generate the automated email by creating an R output in Displayr</span></h2>
<p>Next, to generate the automated email, you will need to create an R Output in Displayr.</p>
<p>Add the following to the <span>R CODE</span> box which loads the R libraries needed to create and send the email.</p>
<pre>
require(httr)
require(jsonlite)
require(flipTime)
</pre>
<p>The next line will determine how frequently to run the code and therefore send the email. This line ensures that the code is re-run every 24 hours and that the dashboard is automatically updated to show the latest results.</p>
<pre>
UpdateEvery(24, &quot;hours&quot;, options = &quot;snapshot&quot;)
</pre>
<p>Add the next line with your SendGrid the API Key entered in the quotes.</p>
<pre>
key1 = &quot;your_api_key&quot; #enter your API Key here
</pre>
<h3>Specify the email parameters and construct the automated message</h3>
<p>Next, the email parameters are specified and the email message is constructed. To do this, enter the recipient’s email address in the first line (<span>to.email</span>). It is a good idea to first enter your own email address here so you can test if the script is working as expected. The sender’s email address is entered in the second line and can be any email address you choose (<span>from.email</span>). You can also specify the email <em>subject</em> and <em>message</em> <i>body </i>here. In the previous step, I described how to automatically write the content of the body. Alternatively, you could replace <span>body</span> with a static message in the fourth line of code below (e.g., <span>message.body= “Hello</span><span> here.”</span>).</p>
<pre>
to.email = &quot;recipient@domain.com&quot;
from.email = &quot;sender@domain.com&quot; 
subject = &quot;Testing Sendgrid on Displayr&quot;
message.body = body

msg = sprintf('{\&quot;personalizations\&quot;:
        [{\&quot;to\&quot;: [{\&quot;email\&quot;: \&quot;%s\&quot;}]}],
          \&quot;from\&quot;: {\&quot;email\&quot;: \&quot;%s\&quot;},
          \&quot;subject\&quot;: \&quot;%s&quot;,
          \&quot;content\&quot;: [{\&quot;type\&quot;: \&quot;text/plain\&quot;,
          \&quot;value\&quot;: \&quot;%s\&quot;}]}', to.email, from.email, subject, message.body)
</pre>
<p>The final bit of code is the actual SendGrid API call which sends the email.</p>
<p>Note, if you want to limit emails sends only to a specific trigger event, it is as simple as adding a plain-old <span>if</span> statement before this code.</p>
<pre>
pp = POST(&quot;https://api.sendgrid.com/v3/mail/send&quot;,
        body = msg,
        config = add_headers(&quot;Authorization&quot; = sprintf(&quot;Bearer %s&quot;, key1),
                        &quot;Content-Type&quot; = &quot;application/json&quot;),
        verbose())
</pre>
<p>Check the <strong>Automatic</strong> check box next to the <span> <span><strong>Calculate</strong></span> </span>button to run the code. You should receive an email at the recipient email address you specified in the code.</p>
<hr>
<h2><span>Step 6: Customize formatting using HTML (Optional) <em> </em></span></h2>
<p>You may want to apply some custom formatting to your emails rather than just sending them as plain text. To do this, you only need to change the content parameter line in the R code above from “text/plain” to “text/html”.</p>
<pre>
\&quot;content\&quot;: [{\&quot;type\&quot;: \&quot;text/html\&quot;,
</pre>
<p>You can now use standard HTML formatting tags in your message body text. For example, you can replace the <span>body </span>variable above with the following to generate an HTML-styled email.</p>
<p>body = paste(“<p>Dear Tim,</p>”,<br>
“<p>Here are the latest results from your NPS survey:</p>”,<br>
“<ul><li>The highest NPS score this month was <strong>”, max.value, “</strong> for <strong>”, max.label, “</strong>.</li>”,<br>
“<li>The lowest NPS score this month was <strong>”, min.value, “</strong> for <strong>”, min.label,”</strong>.</ul>”,<br>
“<p>Click <a rel="nofollow" href="https://www.r-bloggers.com/automatically-write-and-email-reports-with-r-sendgrid-displayr/’https://app.displayr.com/Dashboard?id=53c67902-3f3f-4c06-bcfd-d6c977d0ef99′" target="_blank">here</a> for the full report.</p>”,<br>
“<p>Kind regards,<br>Tim</p>”)
<p>The following email will be generated.</p>
<p><img sizes="(max-width: 505px) 100vw, 505px" src="https://i2.wp.com/www.displayr.com/wp-content/uploads/2017/09/html-nps-email.png?w=450&ssl=1" alt="r generate email html" class="wp-image-3369" data-recalc-dims="1"></p>
<p>You can find more information on basic HTML styling options at <a rel="nofollow" href="https://www.w3schools.com/html/html_styles.asp" target="_blank">https://www.w3schools.com/html/html_styles.asp</a>.</p>
<hr>
<h2><span>You can automatically write and email reports yourself here</span></h2>
<p>You can explore the example used in this post to <a rel="nofollow" href="https://app.displayr.com/Try/Sending%20Automated%20Emails" target="_blank">automatically write and email reports</a>. Just click the link and sign in to Displayr first.</p>
<hr>
<p> </p>
<p> </p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://www.displayr.com/automatically-write-email-reports-using-r-sendgrid-displayr/?utm_medium=Feed&utm_source=Syndication"> R – Displayr</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/3Dlo-O2Wzr4" height="1"></a></div>