---
title: "Sending Messages With Gmailr"
output: rmarkdown::html_vignette
vignette: >
%\VignetteEngine{knitr::rmarkdown}
%\VignetteIndexEntry{Sending Messages With Gmailr}
%\usepackage[utf8]{inputenc}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
eval = getRversion() >= "4.1"
)
```
```{r setup, message = FALSE}
library(gmailr)
```
## Constructing a MIME message
### Text
First we will construct a simple text only message
```{r sending_messages_simple}
text_msg <- gm_mime() |>
gm_to("james.f.hester@gmail.com") |>
gm_from("me@somewhere.com") |>
gm_text_body("Gmailr is a very handy package!")
```
You can convert the message to a properly formatted MIME message using `as.character()`.
```{r sending_messages_simple_print}
strwrap(as.character(text_msg))
```
### HTML
You can also construct html messages. It is customary to provide a text
only message along with the html message, but with modern email clients this is
not strictly necessary.
```{r sending_messages_html}
html_msg <- gm_mime() |>
gm_to("james.f.hester@gmail.com") |>
gm_from("me@somewhere.com") |>
gm_html_body("Gmailr is a very handy package!")
```
### Attachments
You can add attachments to your message in two ways.
1. If the data is in a file, use `gm_attach_file()`. The mime type is
automatically guessed by `mime::guess_type`, or you can specify it yourself
with the `type` parameter.
```{r sending_messages_attachments_2}
write.csv(file = "iris.csv", iris)
msg <- html_msg |>
gm_subject("Here are some flowers") |>
gm_attach_file("iris.csv")
```
2. If the data are already loaded into R, you can use `gm_attach_part()` to attach the binary data to your file.
```{r sending_messages_attachments_1}
msg <- html_msg |>
gm_attach_part(part = charToRaw("attach me!"), name = "please")
```
### Including images
You can also add use attached images in HTML by setting the Content ID feature
of mime emails. This can be done by referencing the image via a `` tag using the `id` argument of `send_file()`. The tag value can
by any unique identifier. E.g. here is an example of including a ggplot2 image
```{r}
# First create a plot to send, and save it to mtcars.png
mtcars$gear <- as.factor(mtcars$gear)
png("mtcars.png", width = 400, height = 400, pointsize = 12)
with(
mtcars,
plot(hp,
mpg,
col = as.factor(gear),
pch = 19,
xlab = "Horsepower",
ylab = "Miles / gallon"
)
)
legend("topright",
title = "# gears",
pch = 19,
col = seq_along(levels(mtcars$gear)),
legend = levels(mtcars$gear)
)
dev.off()
# Next create an HTML email that references the plot as 'foobar'
email <- gm_mime() |>
gm_to("someaddress@somewhere.com") |>
gm_from("someaddress@somewhere.com") |>
gm_subject("Cars report") |>
gm_html_body(
'