gmailR - отправить несколько писем через R с вложением

Я выяснил, как отправить одно электронное письмо через R с вложением и показать тело электронного письма (кажется, это обычная проблема). Однако я хотел бы следовать методу Дженни Брайан по отправке нескольких электронных писем во время так же прикрепил файл.

Отправка одного письма с вложением и сообщением.

msg <- "this is the message of the email"
test_email <- mime() %>%
  to("[email protected]") %>%
  from("from@gmail") %>%
  subject("subject goes here") %>%
  body(msg) %>%
  attach_file("29697.html", type = "html")
test_email <- attach_part(test_email, msg)
send_message(test_email)

Чтобы имитировать приведенный выше код, но с примером Дженни, у меня есть следующее:

addresses <- read_csv("addresses.csv") #contains a column for 'name' and 'email'
email_sender <- 'First Last <[email protected]>' # your Gmail address
msg <- "this is the message of the email"

edat <- addresses %>%
  mutate(
    To = sprintf('%s <%s>', name, email),
    From = email_sender,
    Subject = sprintf('Mark for %s', name),
    body = msg,
    attach_file = sprintf('%s.html, type = html', name))

edat <- edat %>%
  select(To, From, Subject, body, attach_file)

emails <- edat %>%
  pmap(mime)

safe_send_message <- safely(send_message)

sent_mail <- emails %>%
  map(safe_send_message)

В приведенном выше примере создается список для формирования компонентов файловой структуры mime, которую использует gmailR, однако он не прикрепляет файл, как это делает один пример выше. Я попытался структурировать функцию attach_file аналогичным образом, однако она не помещает ее в элемент списка для пантомимы таким же образом, как вызывает ее отдельно, как в единственном примере выше, где она помещает ее в раздел parts элемента списка. . Заранее спасибо, если кто сталкивался с этим.


person Morgan DeBusk-Lane    schedule 18.03.2019    source источник


Ответы (2)


Используя код из предложения dipetkov, я изменил его, добавив вложение и сообщение для отправки одного электронного письма.

library("tidyverse")
library("gmailr")

msg <- "this is the message of the email"

prepare_and_send <- function(sender, recipient,
                             title, text,
                             attachment) {
  email <- mime() %>%
    to(recipient) %>%
    from(sender) %>%
    subject(title) %>%
    html_body(text) %>%
    attach_file(attachment, type = "html")
  email <- attach_part(email, msg) %>%
    send_message() 
}

# Test that function works to send one email
prepare_and_send("sender@gmail", "to@gmail", "some subject",
                 "some text", "20558.html")

Сделав еще один шаг, я немного изменил его, чтобы перебирать серию электронных писем, хранящихся в фрейме данных «адреса».

#Iterate it ----
addresses %>%
  mutate(
    to = sprintf('%s <%s>', name, email),
    from = email_sender,
    subject = sprintf('Mark for %s', name),
    html_body = msg,
    attachment = sprintf('%s.html', name)) %>%
  mutate(x = pmap(list(from, to, subject, html_body, attachment),
                  safely(prepare_and_send)))
person Morgan DeBusk-Lane    schedule 19.03.2019
comment
У меня та же проблема, но я вижу, что базовый код Дженни тоже не работает. Это работает для вас? mime() %>% to("[email protected]") %>% from("[email protected]") %>% html_body("<b>Gmailr</b> is a <i>very</i> handy package!") -> html_msg; write.csv(file = "iris.csv", iris); html_msg %>% subject("Here are some flowers") %>% attach_file("iris.csv") -> file_attachment . - person Lazarus Thurston; 23.03.2019

Иногда проще, хотя, возможно, и не так элегантно, написать функцию, которая выполняет интересующее действие для одной строки таблицы. А затем используйте map/map2/pmap или walk/walk2/pwalk для повторного применения этой функции.

library("tidyverse")
library("gmailr")

# Create two empty attachment files needed for example
file.create("A.html")
#> [1] TRUE
file.create("B.html")
#> [1] TRUE

test_send_message <- function(msg) {
  # Doesn't actually send any emails
  print(strwrap(as.character(msg)))
}

prepare_and_send <- function(sender, recepient,
                             title, text,
                             attachment) {
  email <- mime() %>%
    to(sender) %>%
    from(recepient) %>%
    subject(title) %>%
    text_body(text) %>%
    attach_file(attachment, type = "html") %>%
    test_send_message()
}

# Test that function works to send one email
prepare_and_send("[email protected]", "from@gmail", "some subject",
                 "some text", "A.html")
#>  [1] "MIME-Version: 1.0\r Date: Mon, 18 Mar 2019 21:32:20 GMT\r To:"        
#>  [2] "[email protected]\r From: from@gmail\r Subject: some subject\r"            
#>  [3] "Content-Type: multipart/mixed;"                                       
#>  [4] "boundary=2c47d060a267bfdca54a1fdfe0c4ecaf\r Content-Disposition:"     
#>  [5] "inline\r \r MIME-Version: 1.0\r Date: Mon, 18 Mar 2019 21:32:20 GMT\r"
#>  [6] "Content-Type: text/plain; charset=utf-8; format=flowed\r"             
#>  [7] "Content-Transfer-Encoding: quoted-printable\r Content-Disposition:"   
#>  [8] "inline\r \r some text\r --2c47d060a267bfdca54a1fdfe0c4ecaf\r"         
#>  [9] "MIME-Version: 1.0\r Date: Mon, 18 Mar 2019 21:32:20 GMT\r"            
#> [10] "Content-Type: html; name=A.html\r Content-Transfer-Encoding:"         
#> [11] "base64\r Content-Disposition: inline; filename=A.html;"               
#> [12] "modification-date=Mon, 18 Mar 2019 21:32:20 GMT\r \r \r"              
#> [13] "--2c47d060a267bfdca54a1fdfe0c4ecaf--\r"

# Then try to send multiple emails
addresses <- tribble(
  ~name, ~email,
  "A", "[email protected]",
  "B", "[email protected]"
)

email_sender <- 'First Last <[email protected]>'
msg <- "this is the message of the email"

addresses %>%
  mutate(
    To = sprintf('%s <%s>', name, email),
    From = email_sender,
    Subject = sprintf('Mark for %s', name),
    body = msg,
    attachment = sprintf('%s.html', name)) %>%
  mutate(x = pmap(list(To, From, Subject, body, attachment),
                   safely(prepare_and_send)))
#>  [1] "MIME-Version: 1.0\r Date: Mon, 18 Mar 2019 21:32:20 GMT\r To: A"      
#>  [2] "<[email protected]>\r From: First Last <[email protected]>\r Subject: Mark"    
#>  [3] "for A\r Content-Type: multipart/mixed;"                               
#>  [4] "boundary=bd435d3f3bb00aee58b776142a512702\r Content-Disposition:"     
#>  [5] "inline\r \r MIME-Version: 1.0\r Date: Mon, 18 Mar 2019 21:32:20 GMT\r"
#>  [6] "Content-Type: text/plain; charset=utf-8; format=flowed\r"             
#>  [7] "Content-Transfer-Encoding: quoted-printable\r Content-Disposition:"   
#>  [8] "inline\r \r this is the message of the email\r"                       
#>  [9] "--bd435d3f3bb00aee58b776142a512702\r MIME-Version: 1.0\r Date: Mon,"  
#> [10] "18 Mar 2019 21:32:20 GMT\r Content-Type: html; name=A.html\r"         
#> [11] "Content-Transfer-Encoding: base64\r Content-Disposition: inline;"     
#> [12] "filename=A.html; modification-date=Mon, 18 Mar 2019 21:32:20 GMT\r"   
#> [13] "\r \r --bd435d3f3bb00aee58b776142a512702--\r"                         
#>  [1] "MIME-Version: 1.0\r Date: Mon, 18 Mar 2019 21:32:20 GMT\r To: B"      
#>  [2] "<[email protected]>\r From: First Last <[email protected]>\r Subject: Mark"    
#>  [3] "for B\r Content-Type: multipart/mixed;"                               
#>  [4] "boundary=aa10620651c2281647a4fba0dc392694\r Content-Disposition:"     
#>  [5] "inline\r \r MIME-Version: 1.0\r Date: Mon, 18 Mar 2019 21:32:20 GMT\r"
#>  [6] "Content-Type: text/plain; charset=utf-8; format=flowed\r"             
#>  [7] "Content-Transfer-Encoding: quoted-printable\r Content-Disposition:"   
#>  [8] "inline\r \r this is the message of the email\r"                       
#>  [9] "--aa10620651c2281647a4fba0dc392694\r MIME-Version: 1.0\r Date: Mon,"  
#> [10] "18 Mar 2019 21:32:20 GMT\r Content-Type: html; name=B.html\r"         
#> [11] "Content-Transfer-Encoding: base64\r Content-Disposition: inline;"     
#> [12] "filename=B.html; modification-date=Mon, 18 Mar 2019 21:32:20 GMT\r"   
#> [13] "\r \r --aa10620651c2281647a4fba0dc392694--\r"
#> # A tibble: 2 x 8
#>   name  email   To       From        Subject body         attachment x     
#>   <chr> <chr>   <chr>    <chr>       <chr>   <chr>        <chr>      <list>
#> 1 A     a@gmai~ A <a@gm~ First Last~ Mark f~ this is the~ A.html     <list~
#> 2 B     b@gmai~ B <b@gm~ First Last~ Mark f~ this is the~ B.html     <list~

Создано 18 марта 2019 г. с помощью пакета reprex (v0.2.1)

person dipetkov    schedule 18.03.2019