Sending email from Outlook in R

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!


Comments

21 responses to “Sending email from Outlook in R”

  1. Viktoriia Avatar
    Viktoriia

    Extremely helpful!

  2. Viktoriia Avatar
    Viktoriia

    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

    1. Hi Viktoriia,

      Have a look at Microsoft’s documentation at:

      https://docs.microsoft.com/en-us/office/vba/api/outlook.mailitem

      You might find what you looking for there.

    2. hi Viktoriia,

      Did you figure out a solution?

    3. I am facing a similar issue, any tips?

  3. Melissa Salazar Avatar
    Melissa Salazar

    Wow. Thanks for this updated and thorough tutorial!

  4. Luis Avatar

    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. Hi Luis;

      Yes there is.

      Instead of using Email$Send() in your script, use Email$Display() instead.

      1. Melissa Salazar Avatar
        Melissa Salazar

        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.

        1. Thanks Melissa, I’ve updated the instruction to reflect that change.

  5. Alexis Avatar
    Alexis

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

    1. Hi Alexis

      Have a look at the documentation for the SendUsingAccount property:

      https://docs.microsoft.com/en-us/office/vba/api/outlook.mailitem.sendusingaccount

      It should let you specify the account the message is sent from.

  6. Kevin Avatar

    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

  7. 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

  8. Matt Avatar

    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.

  9. Meenu Avatar

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

    1. You just need to concatenate them together with a semicolon separating the individual email addresses.

  10. Jacob Avatar

    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. Luis Avatar

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

      Jacbob, do you find a way to solve it?

      Thanks

  11. Edoardo Avatar
    Edoardo

    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

  12. Peter

    Altough I have two mailboxes, I want to place mails, that I send from the secondary mailbox, in the sent-folder of the secondary mailbox. In the following code I use the command

    outMail[[“SaveSentMessageFolder”]] <- outApp[["Session"]]$Folders("secondary@outlooksend.at")$Folders("Gesendete Elemente")

    afterwards I get the following error

    80020009
    No support for InterfaceSupportsErrorInfo
    checkErrorInfo -2147352567
    Error: Ausnahmefehler aufgetreten.

    Can You tell me the correct syntax.

    require(RDCOMClient)
    OutApp <- COMCreate("Outlook.Application")
    outMail <- OutApp$CreateItem(0)
    outMail[["to"]] <- "peter.test@checkoutlook.at"
    outMail[["subject"]] <- "TEST"
    #outMail[["body"]] <- "This is a TEST"
    outMail[["bodyformat"]] <- 2
    outMail[["SentOnBehalfOfName"]] <- "secondary@outlooksend.at"
    outMail[["HTMLbody"]] <- '<FONT FACE="Trebuchet MS"Sehr geehrte Damen und HerrenDas ist ein TestBeim Datenimport sind folgende Fehler aufgetreten:’
    outMail[[“SaveSentMessageFolder”]] <- outApp[["Session"]]$Folders("secondary@outlooksend.at")$Folders("Gesendete Elemente")
    outMail$Send()

    Thanks!

Leave a Reply

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