I have a data frame of names and mails, and I would i like to create a loop where R sends a mail to all of these people but with their respective names using the RDCOMClient library. The data frame is
df <- data.frame("Name" = c("Name1", "Name2"), "Mail" = c("mail1@mail.com", "mail2@mail.com"))
As I have just used Python in an exam project, I created loops several times with mulitple variables, such as:
for i,j in zip(df[1], df[2])
My code would ideally be something like
for (mail in df$Mail, name in df$Name) {
outApp <- COMCreate("Outlook.Application")
outMail = outApp$CreateItem(0)
outMail[["To"]] = mail
outMail[["subject"]] = "Subject"
outMail[["body"]] = paste(" Dear", name, "\n \n bla bla bla.")
outMail$Send()
Sys.sleep(0.5)
if (mail == df$Mail[-1]) cat("Done!")
}
This, however, gives an error.
The reason I would like to use a loop is for two reasons:
If you have other suggestions (I have seen several recommendations on the lapply, sapply, etc. packages) they are very welcom!
I hope there's someone out there who knows just what to do.
Thanks in advance,
Emil
I cannot reproduce your question cause I am not on windows but here is an example using the package mailR
.
library(mailR)
library(purrr)
df <- tibble("Name" = c("Name1", "Name2"), "Mail" = c("mail1@mail.com", "mail2@mail.com"))
mail_fun <- function(name, mail){
send.mail(from = "sender@gmail.com",
to = mail,
subject = "Subject of the email",
body = paste(" Dear", name, "\n \n bla bla bla."),
smtp = list(host.name = "aspmx.l.google.com", port = 25),
authenticate = FALSE,
send = TRUE)
Sys.sleep(0.5)
print("Done!")
}
mail_fun("filip", "filip.wastberg@ferrologic.se")
map2(df$Name, df$Mail, ~mail_fun(name = .x, mail = .y))
This should get you an overall idea how to put your code in a function and then use purrr
to iterate over a data.frame.