Friday 20 May 2016

send emails from R through Outlook


This assumes Outlook Application is installed and your account is set up etc...

Also, you may need to restart Outlook after installing the package in R, if you get an error like 'Error: Exception occurred.'.


library(RDCOMClient)

OutApp <- COMCreate("Outlook.Application")  
outMail = OutApp$CreateItem(0) 

outMail[["To"]] = "recipient's email address" 
outMail[["subject"]] = "subject" 
outMail[["body"]] = "body text" 

outMail$Send()



To send emails to multiple recipients, use semicolon (;) to separate email addresses:

OutApp <- COMCreate("Outlook.Application") 
outMail = OutApp$CreateItem(0)

outMail[["To"]] = "recipient's email address 1; recipient's email address 2"
outMail[["subject"]] = "subject" 
outMail[["body"]] = "body text" 

outMail$Send()



To send emails with attachment(s):

OutApp <- COMCreate("Outlook.Application") 
outMail = OutApp$CreateItem(0)

outMail[["To"]] = "recipient's email address"
outMail[["subject"]] = "subject" 
outMail[["body"]] = "body text" 

outMail[["Attachments"]]$Add("full path to file")     
#e.g. "C:/Users/Documents/someFile.txt"
#note the use of forward slash instead of back slash as you'd normally do in R when setting path to the attachment 

outMail$Send()



To embed table within the body of the email:
library(pander) 

panderOptions('table.split.table', Inf)

OutApp <- COMCreate("Outlook.Application") 
outMail = OutApp$CreateItem(0)

outMail[["To"]] = "recipient's email address"
outMail[["subject"]] = "subject" 
outMail[["body"]] = paste("Hello!", "", "The below summarises xxx:", pandoc.table.return(data.frame(V1 = 1:5, V2 = LETTERS[1:5])), sep = "\n")

outMail$Send()



3 comments:

  1. mark mail is repository of emails. It is a big collection of old emails threads to problems based in open source projects like tomcat, apache, dovecot etc


    ReplyDelete
  2. The specialized partners of Gmail took a stab at everything to make that guests comprehend the working of Gmail. Once the clients see how Gmail parcels and its different elements they will have the capacity to handle the Gmail account in a vastly improved way. They will likewise have the capacity to determine certain straightforward issues all alone. http://www.huffingtonpost.com/entry/the-importance-of-online-gmail-support-services-in_us_57ef511ae4b0972364deb40b

    ReplyDelete
  3. Hi, Love your blog post. Thank for the detail. Have you explored any way to add the body with Rich text Formatting or HTML Formatting? Let me know
    Thanks
    Vivek

    ReplyDelete