When setting up automated reporting workflows, a key component is distributing the report to the various stakeholders so they can review it.  One useful technique is to send a “push notification” by email to alert everyone that a report or analysis task has just been completed.  Luckily, it isn’t hard to send out email from R by using Microsoft Outlook.

Prerequisites

This technique will only work on Windows computers with Outlook installed, and requires the RDCOMClient package.  You can install it with the following command:

install.packages("RDCOMClient")

As of the time of writing, the RDCOMClient package isn’t available in CRAN for all versions of R.  If you receive an error such as:

Warning in install.packages :

  package ‘RDCOMClient’ is not available (for R version 3.5.1)

You will need to install DCOMClient from the source repository with:

install.packages("RDCOMClient", repos = "http://www.omegahat.net/R")

Sending plain text email

Sending a plain text email to someone from R is easy!  All you need to do is:

# Load the DCOM library
library (RDCOMClient)

# Open Outlook
Outlook <- COMCreate("Outlook.Application")

# Create a new message
Email = Outlook$CreateItem(0)

# Set the recipient, subject, and body
Email[["to"]] = "recipient1@test.com; recipient2@test.com; recipient3@test.com"
Email[["cc"]] = ""
Email[["bcc"]] = ""
Email[["subject"]] = "Quarterly Sales Analysis Updated"
Email[["body"]] = 
  "The quarterly sales analysis has been updated.  
  You can find it at: D:\\Reports\\Sales Analysis.xlsx"

# Send the message
Email$Send()

# Close Outlook, clear the message
rm(Outlook, Email)

Sending HTML email

If you want to format your message so it looks cleaner and take advantage of improved formatting you can also send HTML messages using the htmlbody instead of the body attribute:

# Load the DCOM library
library (RDCOMClient)

# Open Outlook
Outlook <- COMCreate("Outlook.Application")

# Create a new message
Email = Outlook$CreateItem(0)

# Set the recipient, subject, and body
Email[["to"]] = "recipient1@test.com; recipient2@test.com; recipient3@test.com"
Email[["cc"]] = ""
Email[["bcc"]] = ""
Email[["subject"]] = "Quarterly Sales Analysis Updated"
Email[["htmlbody"]] =
  "<h1>Quarterly Sales Analysis</h1>
  <p>The quarterly sales analysis has been updated.</p>
  <p>You can find it at 
    <a href='file:\\\D:\\Reports\\Sales Analysis.xlsx'>
      D:\\Reports\\Sales Analysis.xlsx
    </a>
  </p>"

# Send the message
Email$Send()

# Close Outlook, clear the message
rm(Outlook, Email)

Adding attachments

Suppose that you have a data frame or file that you would like to send as an attachment to your message.  All you need to do is add the attachments.add attribute to your email object and pass it the path of the file you want to attach.

# Attach a file to the message
Email[["attachments"]]$Add("D:\\Reports\\Sales Analysis.xlsx")

Setting the importance and sensitivity

You can also set the importance and sensitivity of the message using the importance and sensitivity attributes.  Note that the importance and sensitivity are expressed as integers:

Importance

  1. Low
  2. Normal (default)
  3. High

Sensitivity

  1. Normal (default)
  2. Personal
  3. Private
  4. Confidential
# Set the importance
# 0 - Low, 1 - Normal, 2 - High
Email[["importance"]] = "2"

# Set the sensitivity
# 0 - Normal, 1 - Personal, 2 - Private, 3 - Confidential
Email[["sensitivity"]] = "3"

Send messages from an alternate account

If you have permission to send messages on the behalf of someone else in your organization, you can use the sentonbehalfofname attribute to specify which email address you want to message to be sent from.

# Send the message from an alternate account
Email[["sentonbehalfofname"]] = "alternate-sender@test.com"

Request read and delivery receipts

In order to check whether your message was successfully delivered and / or read, you can request read and delivery receipts by setting the readreceiptrequested and originatordeliveryreportrequested attributes to true.

# Request a read receipt
Email[["readreceiptrequested"]] = TRUE

# Request a delivery receipt
Email[["originatordeliveryreportrequested"]] = TRUE

Further ways to take advantage of email from R

There are a number of ways you can integrate email into your R workflows further to increase productivity:

  • For the sake of clarity, I used fixed strings to set the recipients in the examples above.  You could also use a (dynamically generated) semicolon separated vector of email addresses to specify who should receive the messages.
  • Likewise you could also incorporate the results of your analysis into the actual subject line or body by using the paste() function.  Receiving a message that says “Quarterly Sales Analysis Updated – 33% YoY Increase” is a lot more likely to get attention!
  • You can use R’s markdown capability to compose and send information rich HTML messages quickly and easily.

Want to learn more? Read Advanced email in R: embedding images and markdown to learn how to use Markdown to create messages and add embedded images.

Need help automating your reporting workflows, or want to share the latest trick you learned?  Reach out to me by leaving a comment or using the contact form and I would be happy to hear from you!

20 Replies to “Sending email from Outlook in R

  1. The outlook emails have 2 type of sensitivity l, the one you have shown and another one is Azure Information protection labels. Do you know by any ch ace how to access the latter one directly from R code ? Thank you in advance

  2. Hi! Thank you so mucho for the tutorial.

    Is there a way to just prepare the email in a pop up window, in order to check the attatchments before send?

      1. This worked perfectly until today I was getting the error:
        80020009
        No support for InterfaceSupportsErrorInfo
        checkErrorInfo -2147352567
        Error: Exception occurred.
        I changed the commas in the “To” line to semicolons and it worked.

  3. I have multiple email addresses attached to my Outlook application, is there a way to define which one the email is being sent from?

  4. Hello, great guide. I can create and send emails using this method, however I’m unable to add any attachments to my emails! Do you have any insight into why this might be?

    The error I’m receiving is: 80020009; No support for InterfaceSupportsErrorInfo; checkErrorInfo -2147352567

  5. Hi Sean,

    Thank you for the tutorial. I have an issue when I start opening outlook
    # Open Outlook
    Outlook <- COMCreate("Outlook.Application")

    I got below error message

    Error: Invalid class string
    In addition: Warning message:
    In getCOMInstance(name, force = TRUE, silent = TRUE) :
    Couldn't get clsid from the string

    I went through the documentation but I couldn't solve this issue.
    I appreciate your support in this issue.

    Regards,
    Mohamed

  6. Hi Sean,
    Thanks for the tutorial. Any thoughts on why Email$Display() works great, while Email$Send() produces the following error (this is produced when using a similar script as you described above):
    80004004
    No support for InterfaceSupportsErrorInfo
    checkErrorInfo -2147467260
    Error: Operation aborted

    I cant find any reading or others posting with the same issue, and any help would be appreciated.

  7. How to extract email ids from a data frame column and send mail using the Email[[To]] function?

  8. Hello, I am trying to use this and anytime I run the line “Email = Outlook.CreateItem(0)” my session crashed whether I am in RGui or R Studio. Any Idea what would cause this? I am running version 4.1.2 and the error message says “R Encountered a fatal Error. The session was terminated.” Thank you for the help in advance!

    1. Hello, I also got the session crash using R 4.1.2.

      Jacbob, do you find a way to solve it?

      Thanks

  9. Hello I have one question, if you want to reply for a specific email with R, how you can do it?

    Thanks por your post it’s very interesting!

    Thanks

Leave a Reply to Viktoriia Cancel reply

Your email address will not be published. Required fields are marked *