gpt4 book ai didi

r - gmailR - 通过 R 发送多封带附件的电子邮件

转载 作者:行者123 更新时间:2023-12-05 06:27:30 26 4
gpt4 key购买 nike

我已经弄清楚如何通过 R 发送一封带有附件的电子邮件并显示电子邮件的正文(似乎是一个常见问题)。但是,我想关注 Jenny Bryan's method发送多封电子邮件,同时还附加一个文件。

发送一封带有附件和消息的电子邮件。

msg <- "this is the message of the email"
test_email <- mime() %>%
to("to@gmail.com") %>%
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)

为了模仿上面的代码,但是以 Jenny 的例子,我有以下代码:

addresses <- read_csv("addresses.csv") #contains a column for 'name' and 'email'
email_sender <- 'First Last <from@gmail.com>' # 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)

上面的示例创建了一个列表以形成 gmailR 使用的 mime 文件结构的组件,但是,它不像上面的单个示例那样附加文件。我试图以类似的方式构造 attach_file 函数,但是,它并没有像上面的单个示例那样单独调用它,将它放在 mime 的列表项中列表项的 parts 部分。如果有人遇到过这个问题,请提前致谢。

最佳答案

使用 dipetkov's 中的代码建议,我将其修改为同时包含附件和消息以发送一封电子邮件。

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)))

关于r - gmailR - 通过 R 发送多封带附件的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55226676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com