Yuriy Barvinchenko
Yuriy Barvinchenko

Reputation: 1595

How I can add cc when sending email from R with SendGrid

I'd like to send emails from R with many addresses in "to" and "cc"

Following this example https://www.r-bloggers.com/automatically-write-and-email-reports-with-r-sendgrid-displayr/ I can send email to 1 address.

After some experiments I cam send email to few readers in "to" with code like this (actual API key and emails are removed)

library(httr)
library(jsonlite)

body = paste("\\nDear friend,",
             "\\n\\n",
             "\\n\\nI'm testing email.",
             "\\n\\n",
             "\\n\\nKind regards,",
             "\\n\\nYuriy",sep="")


key1       <-  "SG.****" #enter your API Key here

readers <- c("[email protected]",  "[email protected]")
copiers <- c("[email protected]",  "[email protected]")


to.email   <-  paste0('{\"email\": \"', 
                      paste( readers, collapse = '\"}, {\"email\": \"') , 
                      '\"}')
cc.email   <-  paste0(' {\"email\": \"',
                      paste(copiers, collapse = '\"}}, {\"cc\":{\"email\": \"'), 
                      '\"}')
from.email <-  "[email protected]"
subject    <-  "Testing Sendgrid"
message.body  <-  body


msg  <- sprintf('{\"personalizations\":
        [{\"to\": [ %s]}],
          \"from\": {\"email\": \"%s\"},
          \"subject\": \"%s",
          \"content\": [{\"type\": \"text/plain\", \"value\": \"%s\"}]
            }', 
                to.email, from.email, subject, message.body)

pp <-  POST("https://api.sendgrid.com/v3/mail/send",
          body = msg,
          config = add_headers("Authorization" = sprintf("Bearer %s", key1),
                               "Content-Type" = "application/json"),
          verbose())

But I can't add few emails in "cc". After reading documentation https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html it tried code below, but I have "Bad request" reply.

msg  <- sprintf('{\"personalizations\":
        [{\"to\": [ %s]}],
        [{\"cc\": [ %s]}],
          \"from\": {\"email\": \"%s\"},
          \"subject\": \"%s",
          \"content\": [{\"type\": \"text/plain\", \"value\": \"%s\"}]
            }', 
                to.email, cc.email, from.email, subject, message.body)

I saw solutions for other languages, but not for R. Any ideas?

Upvotes: 0

Views: 888

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388797

1) Using sendgrid

For sendgrid, we don't need to escape every string with /, it is automatically done. Also it is important to construct the request object correctly.

library(httr)
library(jsonlite)

key1 <- "SG.***"
body = paste0("\\nDear friend,",
          "\\n\\n",
          "\\n\\nI'm testing email.",
          "\\n\\n",
          "\\n\\nKind regards,",
          "\\n\\nRonak")


readers <- c("[email protected]", "[email protected]")
copiers <- c("[email protected]", "[email protected]")
to.email <- paste0('{"email": "',paste(readers,collapse = '"}, {"email": "'),'"}')
cc.email <- paste0('{"email": "',paste(copiers,collapse = '"}, {"email": "'),'"}')
from.email <-  "[email protected]"
subject    <-  "Testing Sendgrid"
message.body  <-  body


msg  <- sprintf('{"personalizations":[{
                  "to": [ %s],
                  "cc": [ %s]
                  }],
                 "from\": {"email": "%s"},
                 "subject\": "%s",
                 "content\": [{"type": "text/plain", "value": "%s"}]
                }', to.email, cc.email, from.email, subject, message.body)

POST("https://api.sendgrid.com/v3/mail/send",
 body = msg,
 config = add_headers("Authorization" = sprintf("Bearer %s", key1),
                      "Content-Type" = "application/json"),
 verbose())

2) Using emayili

Apart from using sendgrid there are lot of packages in R which is used to send emails. I used a new package emayili to send the email and it worked for me.

The reason why I chose it is because :-

  • the package is fairly new and thus overcomes the issues which are present in older packages. The previous packages have lot of difficulty in installation and setting up.

  • using it is very straightforward, easy to use syntax

However, the downside is since it is fairly new it is still not available on CRAN and the package needs to be downloaded from github.

install.packages("curl")
remotes::install_github("datawookie/emayili")

library(emayili)
library(magrittr)
library(curl)


email <- envelope()
email <- email %>%
         from(c("[email protected]", "[email protected]")) %>%
         to("[email protected]") %>%
         cc("[email protected]")

email <- email %>% subject("This is a plain text message!")
email <- email %>% body("Hello!")
smtp <- server(host = "smtp.gmail.com",
           port = 587,
           username = "[email protected]",
           password = "password")
smtp(email, verbose = TRUE)

I tested this on my personal gmail and yahoo account and the mail came through. You might want to add verbose = FALSE if you don't want to flood your console with log messages. Also if you are using gmail you might need to allow access to less secure apps to send the email.

Upvotes: 2

Related Questions