Home > Back-end >  Automatize text in an email from R
Automatize text in an email from R

Time:06-04

I was looking how to send emails from R, but I want to know how to automatize text depending on a table like this one:

  Name       Email              CODE
  <chr>      <chr>             <dbl>
1 Student 1  [email protected]     30
2 Student 2  [email protected]    20
3 Student 20 [email protected]     5

For example, I would like to send different messages with different text depending on the student's names and codes:

Hello Student 20,
your code is 5.

See you.

And the same with Student 1, Student 2, and so on.

CodePudding user response:

Two options:

sprintf("Hello %s your code is %d", df$name, df$code)
[1] "Hello x your code is 12" "Hello y your code is 32"

glue::glue_data(df, "Hello {name} your code is {code}")
Hello x your code is 12
Hello y your code is 32

Data

df = data.frame(name = c('x', 'y'), code = c(12, 32))

CodePudding user response:

You can use \n to add line breaks and have a better formatted text.

E.g. with paste0

msgs <- paste0("Hello ", df$name, ",\nyour code is: ", df$code, ".\n\nSee you.\n")
msgs
## [1] "Hello x,\nyour code is: 12.\n\nSee you.\n"
## [2] "Hello y,\nyour code is: 32.\n\nSee you.\n"

To see how it will look like you can use cat, here is the first message:

cat(msgs[1])

Hello x,
your code is: 12.

See you.
  •  Tags:  
  • r
  • Related