-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsg.R
229 lines (198 loc) · 5.4 KB
/
sg.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
#' Create and send MIME formatted message objects
#'
#' @description
#' Methods for creating and sending MIME messages.
#'
#' @return A MIME object.
#' @export
#' @examples
#' \dontrun{
#' sg_mime() |>
#' sg_from("[email protected]") |>
#' sg_to("[email protected]", "[email protected]") |>
#' sg_cc("[email protected]", "[email protected]") |>
#' sg_bcc("[email protected]", "[email protected]") |>
#' sg_subject("This is the subject") |>
#' sg_body("Hello from sg!") |>
#' sg_attachments("path/to/file1.csv", "path/to/file2.pdf") |>
#' sg_send()
#' }
sg_mime <- function() {
structure(
list(
to = list(),
cc = list(),
bcc = list(),
from = NULL,
subject = NULL,
content = list(),
attachments = list()
),
class = "mime"
)
}
#' Generic for setting the 'from' field
#'
#' @param x A MIME object.
#' @param email The sender's email address.
#' @rdname sg_mime
#' @export
sg_from <- function(x, email) {
UseMethod("sg_from")
}
#' @export
sg_from.mime <- function(x, email) {
x$from <- list(email = email)
x
}
#' Generic for adding recipients to 'to' field
#'
#' @param ... One or more email addresses.
#' @rdname sg_mime
#' @export
sg_to <- function(x, ...) {
UseMethod("sg_to")
}
#' @export
sg_to.mime <- function(x, ...) {
emails <- unlist(rlang::list2(...), recursive = FALSE)
x$to <- lapply(emails, \(email) list(email = email))
x
}
#' Generic for adding recipients to 'cc' field
#' @rdname sg_mime
#' @export
sg_cc <- function(x, ...) {
UseMethod("sg_cc")
}
#' @export
sg_cc.mime <- function(x, ...) {
emails <- unlist(rlang::list2(...), recursive = FALSE)
x$cc <- lapply(emails, \(email) list(email = email))
x
}
#' Generic for adding recipients to 'bcc' field
#' @rdname sg_mime
#' @export
sg_bcc <- function(x, ...) {
UseMethod("sg_bcc")
}
#' @export
sg_bcc.mime <- function(x, ...) {
emails <- unlist(rlang::list2(...), recursive = FALSE)
x$bcc <- lapply(emails, \(email) list(email = email))
x
}
#' Generic for setting the email subject
#' @rdname sg_mime
#' @param subject The email subject.
#' @export
sg_subject <- function(x, subject) {
UseMethod("sg_subject")
}
#' @export
sg_subject.mime <- function(x, subject) {
x$subject <- subject
x
}
#' Generic for setting the email body
#' @rdname sg_mime
#' @param body The body content of the email.
#' @param type The content type (e.g., "text/plain")
#' @export
sg_body <- function(x, body, type = "text/html") {
UseMethod("sg_body")
}
#' @export
sg_body.mime <- function(x, body, type = "text/html") {
x$content <- list(type = type, value = body)
x
}
#' Generic for adding attachments
#' @rdname sg_mime
#' @export
sg_attachments <- function(x, ...) {
UseMethod("sg_attachments")
}
#' @export
sg_attachments.mime <- function(x, ...) {
paths <- unlist(rlang::list2(...), recursive = FALSE)
attachments <-
lapply(paths, function(path) {
content <- base64enc::base64encode(path)
filename <- basename(path)
mime_type <- mime::guess_type(path)
list(
content = content,
filename = filename,
type = mime_type,
disposition = "attachment"
)
})
x$attachments <- c(x$attachments, attachments)
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, api_key = Sys.getenv("SENDGRID_API_KEY")) {
UseMethod("sg_send")
}
#' @export
sg_send.mime <- function(x, api_key = Sys.getenv("SENDGRID_API_KEY")) {
if (is.null(x$from)) {
rlang::abort("The 'from' field is required.")
}
if (length(x$to) == 0) {
rlang::abort("At least one 'to' recipient is required.")
}
if (!is_email_address(x$from)) {
rlang::abort("The 'from' field must contain a valid email address.")
}
validate_recipients <- function(recipients, field_name) {
if (length(recipients) > 0 && !all(sapply(recipients, \(r) is_email_address(r$email)))) {
rlang::abort(paste("One or more invalid email addresses in the", field_name, "field."))
}
}
validate_recipients(x$to, "to")
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,
cc = if (length(x$cc) > 0) x$cc else NULL,
bcc = if (length(x$bcc) > 0) x$bcc else NULL
) |>
Filter(Negate(is.null), x = _)
email <-
rlang::list2(
personalizations = list(personalizations),
from = x$from,
subject = x$subject,
content = list(x$content),
attachments = if (!is.null(x$attachments) && length(x$attachments) > 0) x$attachments else NULL
) |>
Filter(Negate(is.null), x = _)
req <-
httr2::request("https://api.sendgrid.com/v3/mail/send") |>
httr2::req_auth_bearer_token(api_key) |>
httr2::req_body_json(email, auto_unbox = TRUE)
resp <- req |> httr2::req_perform()
if (httr2::resp_status(resp) == 202L) {
rlang::inform("The email is successfully sent!")
}
invisible(email)
}
#' Check if a string is in a valid email format
#'
#' @param email A character string.
#' @return A logical value.
#' @keywords internal
is_email_address <- function(email) {
email_pattern <- "^[[:alnum:]._%+-]+@[[:alnum:].-]+\\.[[:alpha:]]{2,}$"
grepl(email_pattern, email)
}