Emails from R

[This article was first published on R – Insights of a PhD student, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

There are a few packages for sending email directly from R, but I work in a place where none of these work due to strict network settings. To at least partially circumvent this, here’s some code to produce a PowerShell script to send email(s) via Outlook. The PowerShell script can then be run either by a shell call (again, not possible in my workplace) or by right clicking the file and selecting run with PowerShell.


# Addresses 
add <- c("[email protected]", "[email protected]")
subject <- "Testing"

# construct message
# opening
start <- 'Hi, 
how are you?

# main content
body <- '
sent almost exclusively from R 

# signature
sig <- '
And this is my signature

# paste components together
Body <- paste(start, body, sig)

# construct PowerShell code (*.ps1)
email <- function(recip, subject, Body, filename, attachment = NULL, append){
  file <- paste0(filename, ".ps1")
  write('$Outlook = New-Object -ComObject Outlook.Application', file, append = append)
  write('$Mail = $Outlook.CreateItem(0)', file, append = TRUE)
  write(paste0('$Mail.To = "', recip, '"'), file, append = TRUE)
  write(paste0('$Mail.Subject = "', subject, '"'), file, append = TRUE)
  write(paste0('$Mail.Body = "', Body, '"'), file, append = TRUE)
    write(paste0('$File = "', attachment, '"'), file, append = TRUE)
    write('$Mail.Attachments.Add($File)', file, append = TRUE)
  write('$Mail.Send()', file, append = TRUE)
  if(append) write('', file, append = TRUE)

for(i in 1:length(add)){
  file <- paste0("email", i, ".ps1")
  att <- file.path(getwd(), "blabla.txt")
  email(add[i], subject, Body, file, attachment = att) # with attachment
  # email(add[i], subject, Body, file)                 # without attachment
  # email(add[i], subject, Body, file, append = TRUE)  # multiple emails in a single PS file 


Now you can go and run the PowerShell script from within windows explorer.

To leave a comment for the author, please follow the link and comment on their blog: R – Insights of a PhD student. offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)