Sending emails through gmailR grouped by a variable?

Hello. I’m using the gmailR package and a 'for loop' to send emails based off an imported dataset but I need some assistance.

I created a simplified data set example (see image below). This data set has two variables. One variable is Record (unique numeric variable: 1, 2, 3, etc) and the other variable is Section (not unique, categorical: A, B, C, D, etc)

RStudioQuestion

I want to send an email where it states “Record # has been moved to Section X”. However, it should group by the Section value. Each Section should receive only 1 email with 1 message for each record. For example, Section A should receive 1 email with the 3 separate message lines listed for each record (since there are 3 Records for Section A), OR receive 1 email with 3 separate messages but within the same email chain (if that makes sense?)

Here’s my current code.

i<1
for (i in 1:nrow(RDataExample)){

subject<-paste("Moves ", date=Sys.Date(),sep="")

body<-paste("Record ",RDataExample$Record[i]," has been moved to ",RDataExample$Section[i]," on ",date=Sys.Date(),".",sep="")

msg = gm_mime() %>%
gm_from("my email") %>%
gm_to("some email") %>%
gm_subject(subject) %>%
gm_html_body(body)
gm_send_message(msg)
i<i+1
}

The issue is that this code sends a separate email for every single record in the data. Section A receives 3 different emails, but I would like it to receive only 1 email with just 3 lines listed for each record. Do you have any suggestions on how to fix this, so that each Section only gets 1 email pertaining to their Record #s? Thank you for any assistance.

I can't reproduce your code but this illustrates how to construct the email subject, you can apply this to your code.

RDataExample <- data.frame(stringsAsFactors = FALSE,
                           Record = 1:10,
                           Section = c("A", "B", "B", "C", "D", "B", "E", "A", "A", "C"))

for (section in unique(RDataExample$Section)) {
    body <- paste("Record ", 
          RDataExample[RDataExample$Section == section,]$Record,
          " has been moved to ",
          section," on ",
          date = Sys.Date(),".\n", sep = "")
    cat(body, "\n")
}
#> Record 1 has been moved to A on 2020-04-21.
#>  Record 8 has been moved to A on 2020-04-21.
#>  Record 9 has been moved to A on 2020-04-21.
#>  
#> Record 2 has been moved to B on 2020-04-21.
#>  Record 3 has been moved to B on 2020-04-21.
#>  Record 6 has been moved to B on 2020-04-21.
#>  
#> Record 4 has been moved to C on 2020-04-21.
#>  Record 10 has been moved to C on 2020-04-21.
#>  
#> Record 5 has been moved to D on 2020-04-21.
#>  
#> Record 7 has been moved to E on 2020-04-21.
#> 

Created on 2020-04-21 by the reprex package (v0.3.0.9001)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.