Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Send an email via an R function using Mailgun
#' Email a user a report is ready
#'
#' Requires an account at Mailgun: https://mailgun.com
#' Pre-verification can only send to a whitelist of emails you configure
#'
#' @param email Email to send to
#' @param mail_message Any extra info
#'
#' @return TRUE if successful email sent
#' @import httr
#' @export
sendEmail <- function(email = "XXXXX@you.com",
mail_message = "Hello"){
url <- "https://api.mailgun.net/v3/sandbox5f2XXXXXXXa.mailgun.org/messages"
## username:password so api_key is all after the api:
api_key <- "key-c5957XXXXXXXXXXXbb9cf8ce"
the_body <-
list(
from="Mailgun Sandbox <postmaster@sandbox5XXXXXXXXa.mailgun.org>",
to=email,
subject="Mailgun from R",
text=mail_message
)
req <- httr::POST(url,
httr::authenticate("api", api_key),
encode = "form",
body = the_body)
httr::stop_for_status(req)
TRUE
}
@IronistM

This comment has been minimized.

Copy link

commented Apr 13, 2017

I think that at line:23 value mailmessage should be mail_message.

@MarkEdmondson1234

This comment has been minimized.

Copy link
Owner Author

commented Jun 7, 2017

Ah, thanks!

@teguhn

This comment has been minimized.

Copy link

commented Dec 4, 2017

how do you send attachments? thanks

@MarkEdmondson1234

This comment has been minimized.

Copy link
Owner Author

commented Dec 14, 2017

For email attachments, modify above to include HTML files - see the API docs https://documentation.mailgun.com/en/latest/api-sending.html#sending

e.g.

 the_body <-
    list(
      from = from_name,
      to = email,
      subject = subject_line,
      html = html_string
    )
@laresbernardo

This comment has been minimized.

Copy link

commented Apr 19, 2019

Hello!! Really enjoyed this function because I want to get rid of mailR::send.mail() that depends on rJava. But, how can I send attachments with PDFs, ggplots objects, CSVs, and simple HTML files as mailR does? Can you please share a reproducible example? Already have mi API credentials and is working just fine with simple texts.

I think it must have something to do with add_headers("Content-Type" = "multipart/form-data") in the POST function, and something like pdf = upload_file("~/Desktop/myPDF.pdf") inside the the_body list. But haven't succeeded

UPDATE: I got to send an attachment file with what I commented above. But can't send more than one in the same email! Is it possible? tried a list for attachment inside the the_body but doesn't work.

@laresbernardo

This comment has been minimized.

Copy link

commented Apr 20, 2019

Pimped it up a little: https://github.com/laresbernardo/lares/blob/master/R/mails.R
Just need to know how to send multiple attachments for it to fully work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.