Skip to content

feat: enable users to input the API key #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 8 additions & 16 deletions R/sg.R
Original file line number Diff line number Diff line change
Expand Up @@ -152,13 +152,14 @@ sg_attachments.mime <- function(x, ...) {

#' Generic for sending the email
#' @rdname sg_mime
#' @param api_key SendGrid API key. Defaults to the environment variable `SENDGRID_API_KEY` if not provided.
#' @export
sg_send <- function(x) {
sg_send <- function(x, api_key = Sys.getenv("SENDGRID_API_KEY")) {
UseMethod("sg_send")
}

#' @export
sg_send.mime <- function(x) {
sg_send.mime <- function(x, api_key = Sys.getenv("SENDGRID_API_KEY")) {
if (is.null(x$from)) {
rlang::abort("The 'from' field is required.")
}
Expand All @@ -181,6 +182,10 @@ sg_send.mime <- function(x) {
validate_recipients(x$cc, "cc")
validate_recipients(x$bcc, "bcc")

if (!nzchar(api_key)) {
rlang::abort("No API key found, please supply with api_key argument or with SENDGRID_API_KEY env var")
}

personalizations <-
rlang::list2(
to = x$to,
Expand All @@ -201,7 +206,7 @@ sg_send.mime <- function(x) {

req <-
httr2::request("https://api.sendgrid.com/v3/mail/send") |>
httr2::req_auth_bearer_token(get_api_key()) |>
httr2::req_auth_bearer_token(api_key) |>
httr2::req_body_json(email, auto_unbox = TRUE)

resp <- req |> httr2::req_perform()
Expand All @@ -213,19 +218,6 @@ sg_send.mime <- function(x) {
invisible(email)
}

#' Get API key for auth.
#'
#' @param api_key SendGrid API key.
#' @return api_key
#' @keywords internal
get_api_key <- function(api_key = Sys.getenv("SENDGRID_API_KEY")) {
if (!nzchar(api_key)) {
rlang::abort("No API key found, please supply with api_key argument or with SENDGRID_API_KEY env var")
}

api_key
}

#' Check if a string is in a valid email format
#'
#' @param email A character string.
Expand Down
18 changes: 0 additions & 18 deletions man/get_api_key.Rd

This file was deleted.

4 changes: 3 additions & 1 deletion man/sg_mime.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.