I am trying to send an email with attachment using R curl.
If I use the command line, the following succeeds in sending an email via curl from from@mail.com to to@mail.com and attaches the file tester.pdf (note authentication is done using SSL and the password would be horsebatterystaple):
BODY="This is the body of the email..."
SUBJECT="Did you get my last email with the reports?"
curl -v \
--url smtp://the-smtp-server:587 \
--ssl-reqd \
--mail-from from@mail.com \
--mail-rcpt to@mail.com \
--user from@mail.com:horsebatterystaple \
-F '=(;type=multipart/mixed' -F "=$BODY;type=text/plain" \
-F "file=@tester.pdf;type=application/pdf;encoder=base64" -F '=)' \
-H "Subject: $SUBJECT" \
-H "From: Myself <from@mail.com>" \
-H "To: Someone Else <to@mail.com>"
Now I want to translate that to R and the R curl package.
It works without attachments when I use this resource, but I cannot find a way to properly emulate the -F (form) flags.
See my attempt below.
There are no form arguments in the curl options (curl::curl_options("form")) and I do not find example code for curl::form_file() or the mimepost option (=> curl::curl_options("mime")).
Any ideas how to make this work?
Note I am not looking for cmd <- "curl -v --url ..."; system(cmd) type solutions if possible...
h <- curl::new_handle(
verbose = TRUE,
url = "smtp://the-smtp-server:587",
use_ssl = 1,
mail_from = "from@mail.com",
mail_rcpt = "to@mail.com",
username = "from@mail.com",
password = "horsebatterystaple"
)
curl::handle_setheaders(h,
"Subject: Hello World",
"From: Myself <from@mail.com>",
"To: Someone Else <to@mail.com>"
)
curl::curl_fetch_memory(handle = h)
Update
After reading through some more documentation, I also found curl::send_email(), therefore my R code is updated to the following, but the attachment still do not work... (see tries as comments):
conf <- list(smpt_server = "...", ...)
verbose <- TRUE
url <- paste0("smtp://", conf$smtp_server, ":", conf$smtp_port)
message <- glue::glue('From: "{conf$name_from}" <{conf$mail_from}>
To: "{conf$name_to}" <{conf$mail_to}>
Subject: {subject}
Hi there,
this is sent from R curl...')
a <- curl::send_mail(
mail_from = conf$mail_from,
mail_rcpt = conf$mail_to,
message = message, smtp_server = url,
use_ssl = TRUE, verbose = verbose,
username = conf$mail_from, password = conf$password,
# mimepost = "file=@tester.pdf;type=application/pdf;encoder=base64"
# mimepost = form_file("tester.pdf", "application/pdf")
)