Skip to content

Emails from R

April 21, 2017

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("", "")
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.


<UPDATE> The clue to this solving this came from here

From → R

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: