Emailing under Windows using R

Programatically sending an email under Linux is relatively simple. There are several command line clients such as sendmail and mail which are very easy to use. There are also several R packages to help send emails such as {mailr} and {blastula}.
Generally you need access to an SMTP to send messages programatically and this may not be possible in a work setting.
Here's a simple R function to send an email under Windows. It uses vbs scripting to send an email via the Outlook client itself, without needing server parameters.

 1#' Send an email with attachments
 2#'
 3#' Sends an email to a recipient using vbs scripting.
 4#' `body` contains the body of the email and `files` contains a list of files
 5#' to attach.
 6#'
 7#' @param to Recipient email address
 8#' @param subject Subject line
 9#' @param body Body text
10#' @param files List of files to attach
11#'
12#' @export
13lc_send_email <- function(to = NULL, subject = "", body = "", files = list()) {
14
15  if (is.null(to)) return(NULL)
16
17  if (length(files) > 0) {
18    v.files <- unlist(sapply(files, function(f) {
19      paste0('myAttachments.Add "', normalizePath(f), '", olByValue')
20    }))
21  } else {
22    v.files <- ''
23  }
24
25  ## build a vbs script to send an email to user
26  v.outlook_commands <- c(
27    'Dim olApp',
28    'Dim objMailItem',
29    'Dim myAttachments',
30    'Set olApp = CreateObject("Outlook.Application")',
31    'Set objMailItem = olApp.CreateItem(0)',
32    'Set myAttachments = objMailItem.Attachments',
33    paste0('objMailItem.Subject = "', subject, '"'),
34    paste0('objMailItem.To = "', to, '"'),
35    paste0('objMailItem.Body = "', body, '"'),
36    v.files,
37    'objMailItem.Send',
38    'Set olApp = Nothing',
39    'Set objMailItem = Nothing'
40  )
41
42  ## write script to temporary location
43  script_file <- tempfile(fileext = '.vbs')
44  sink(script_file, append = FALSE)
45  cat(v.outlook_commands, sep='\n')
46  sink()
47
48  ## execute script
49  system_script <- paste0('WScript ', normalizePath(script_file))
50  system(system_script)
51
52}