Send Outlook email and Teams messages with R

The Microsoft365R package makes it easy to connect R with Outlook, Teams, OneDrive, and SharePoint. Let’s start with Outlook and Teams.

Send Outlook email and Teams messages with R
Thinkstock

If you analyze data in R and share information via Microsoft 365, I have good news: There is an easy way to connect R with Outlook, Teams, OneDrive, and SharePoint. The Microsoft365R R package, developed by the Microsoft Azure team, includes functions to work with Microsoft 365 APIs from R. 

Here we’ll walk through how to send Outlook email and Teams messages with R.

Microsoft365R is available on CRAN, so you can install it with install.packages("Microsoft365R").

Authenticate R to work with Outlook

The first step is to authenticate R to work with your account. The function for that depends on the Microsoft 365 service and whether it’s in a business or personal account.

To authorize an enterprise Outlook account, for example, load the Microsoft365R package and then use its get_business_outlook() function:

library(Microsoft365R)
my_outlook <- get_business_outlook()

In the code above I am creating a new object my_outlook of class ms_outlook.  

If you’re using a personal Outlook account, use the function get_personal_outlook() instead. 

You may run into a problem with your work account and see an error that authentication failed “due to policies configured by your administrator.” The Microsoft365R authentication vignette has some suggestions on how to deal with this. You can view the vignette by running the base R vignette function vignette("auth", package = "Microsoft365R").

That vignette links to another page with some helpful advice.

Advice includes a Microsoft365R app ID to use for authentication Microsoft Azure GitHub repo

Advice on dealing with Microsoft365R authentication issues.

That app ID in bold is Microsoft’s official app ID. Adding it as an argument to the authentication function sometimes helps with approval:

my_outlook <- get_business_outlook(app = "d44a05d5-c6a5-4bbb-82d2-443123722380")

To reiterate: That app ID isn’t anything from my setup specifically; it’s Microsoft’s official app ID. (And in case anyone from your IT department asks about this, you can truthfully explain that advice came from Microsoft’s own Azure team’s documentation.)

If authentication works, a browser window will pop up asking you to sign into your Microsoft account, and your app will be successfully authenticated.

Send Outlook email with R

There’s a lot you can do with your new Outlook connection, including read and delete emails. But the most interesting one for me is to send email. To do that, start by creating an email object using the create_mail() method of your ms_outlook object, such as:

my_email <- my_outlook$create_email("Body text I want in my email", 
subject = "Email subject", to = "recipient@email.com")

When you run code creating an email object, a draft email should be saved in your Outlook Drafts folder.

There are a couple of other syntaxes you can use to create an email. In the code below, the dollar sign symbol acts like a pipe to chain several methods together. 

my_email <- my_outlook$create_email(content_type = "html")$
set_body("<p>This is my email body <strong>with bold text</strong>.</p>")$
set_subject("My 2nd email subject")$
set_recipients(to = c("recipient1@mail.com", "recipient2@mail.com"))

The above code creates an email object with content type HTML and uses HTML formatting in the message. It also includes multiple recipients. Creating an email object this way will also generate a message that appears in your Outlook Drafts folder. 

Outlook email message from the Drafts folder Sharon Machlis

Email created by R and not yet sent appears in your Outlook Drafts folder.

You can use Markdown instead of raw HTML in the email body if you pair Microsoft365R with the blastula package. You can do this by first loading the blastula package and then saving some Markdown as an R character string. In the example code below, I save some Markdown to a variable called blastula_body_text.

library(blastula)
blastula_body_text <- "This is my email body with _italics text_. As with usual markdown, **two blank lines** create a new paragraph and two asterisks bold text."

Next, turn that character string with markdown formatting into a blastula email object with blastula’s compose_email() function. The character string goes into the body argument, but it’s wrapped in blastula’s md() function so compose_email() knows there is Markdown in the body that needs to be rendered.

blastula_email <- compose_email(
body = md(blastula_body_text)
)

Finally, you create an Outlook email from the blastula email:

outlook_email_from_blastula <- my_outlook$create_email(blastula_email, 
subject = "Markdown with blastula", to = "someone@gmail.com")

I found the need for all three steps to be a bit confusing at first. To recap the blastula-to-Outlook workflow:

  1. Save your markdown in a character string.
  2. Create a blastula email object with compose_email() with your string as the first argument wrapped in md().
  3. Turn the blastula email object into an Outlook email object with create_email().

There are a few more things you can do with email objects, such as add an attachment with the add_attachment() method.

In theory, you should also be able to include inline images when sending your email, but I had mixed success with that so can’t recommend it yet. ! And at the time of this writing, while the Microsoft365R documentation said it is also compatible with the emayili R email package, I couldn't get it to work. Update: Both work now, thanks to a Microsoft365R package revision by package author and maintainer Hong Ooi. 

As of this writing, you'll need to install the development version of Microsoft365R from GitHub with remotes::install_github("Azure/Microsoft365R"); also install emayili from CRAN. Write an R Markdown document as usual including static plots and graphs (JavaScript-based HTML widgets won't work). Then render the markdown file to an HTML file with rmarkdown::render(). 

Create an emayili mail object with code such as

msg <- envelope(
to = "someone@gmail.com",
subject = "My subject",
html = "myfilename.html"
)

where "myfilename.html" is your rendered HTML file.

Then turn that into an outlook email message:

msg <- outlook$create_email(msg)

Sending email is easy with the Outlook email object’s send() method for any outlook email:

msg$send()

Send Teams messages with R

Working with Teams is similar to working with Outlook. Authenticate with the get_team() function, which requires the name or ID of one of your Teams. As with Outlook, this may not always work in an enterprise environment. There is another specific Microsoft app ID — also provided in the Microsoft365R authentication documentation — to try in the authentication function if get_team("Team name or ID") doesn’t work: 

my_team <- get_team("Team name or ID", 
app = "04b07795-8ddb-461a-bbee-02f9e1bf7b46"))

That first argument above should be a specific team name or ID you can access via Teams. The second argument, app ID, is Microsoft’s; everyone would use this same ID to try this method of authentication.

After you authenticate, create a channel object from the team object with the get_channel() method. The code below creates an object for the General channel in my Team.

my_chan <- my_team$get_channel("General")

It’s pretty simple to send a basic text message to a channel, including an attachment if desired, using the channel object’s send_message() method. For example:

my_chan$send_message("Your upcoming weather forecast", 
attachments = "images/temperature_forecast.png")

There are similar authentication and communication functions for OneDrive and SharePoint that will list, upload, and download files. I didn’t have too much success authenticating with those at work, but it was extremely easy to connect to a personal OneDrive account.

For more information on the Microsoft365R package, head to the package repository in Microsoft Azure’s GitHub. And for more R tips, check out the InfoWorld Do More With R page.

Copyright © 2021 IDG Communications, Inc.