본문 바로가기
R

Rmd 문서 G메일로 전송하기 (blastula 패키지)

by 슬통이 2023. 4. 9.
반응형

문서 자동화의 핵심 기능이죠? 데이터에 연결된 보고서를 kniting 할 때마다 내용이 바뀌게 작성하고, 작성된 결과를 메일로 전송하는 방법을 알아보겠습니다.

blastula 패키지를 사용한 Email 보내기 영상

다음은 영상에서 사용한 R코드와 Rmd 코드입니다.

email-automation.R 코드

# 이메일 내용 작성
email_body <- render_email("./email-report.Rmd")

# 이메일 전송
today <- Sys.Date()
this_year <- lubridate::year(today)
this_month <- lubridate::month(today)

# 구글 Gmail
# create_smtp_creds_key(
#     id = "gmail",
#     user = "statisticsplaybook@gmail.com",
#     provider = "gmail",
#     overwrite = T
# )

# 메일 보내기
email_body %>%
  smtp_send(
    from = "statisticsplaybook@gmail.com",
    to = "statisticsplaybook@gmail.com",
    subject = glue::glue("{this_year}년 {this_month}월 슬기로운통계생활 매출 요약"),
    credentials = creds_key(id = "gmail")
  )

 

email report  Rmd 파일

---
title: "summary email"
output: blastula::blastula_email
editor_options: 
  chunk_output_type: console
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
	echo = FALSE,
	message = FALSE,
	warning = FALSE
)
```

```{r logo, echo=FALSE, fig.cap="", fig.align='center', out.width = '35%'}
# knitr::include_graphics("./img/sp-logo.jpg ")
library(cowplot)
logo_path <- "./img/sp-logo.jpg"
logo <- ggdraw() + 
  draw_image(logo_path)
logo
```

```{r data-setup}
library(tidyverse)

# 구글 스프레드시트 가져오기
sales_data <- read_csv("sales_data.csv")
```

```{r date-setup}
today <- Sys.Date()
this_year <- lubridate::year(today)
this_month <- lubridate::month(today)
this_day <- lubridate::day(today)
```

## `r this_year` 년 `r this_month` 월 매출 요약 보고서

### 아이템 별 매출 현황

```{r}
library(tidyverse)
library(gt)
sales_data |> 
    mutate(매출 = 수량 * 가격) |> 
    summarise(총매출 = sum(매출),
              .by = 아이템) |> 
    gt() |> 
    fmt_currency(
        columns = 총매출,
        currency = "KRW",
        decimals = 0
    ) |> 
    as_raw_html()
```

### 월 별 매출 현황

```{r fig.align='center'}
library(tsibble)
library(feasts)

sales_data |> 
    mutate(날짜 = as.Date(날짜)) |> 
    mutate(매출 = (수량 * 가격)/10000) |> 
    group_by(날짜 = lubridate::floor_date(날짜, 'month')) |>
    summarise(총매출 = sum(매출)) |> 
    as_tsibble(index = 날짜) |> 
    autoplot(총매출) +
    scale_x_date(date_breaks = "1 month",
                 date_labels = "%y년\n%m월") +
    theme(axis.text.x = element_text(angle = 0,
                                     hjust = 1)) +
    bbplot::bbc_style() +
    labs(title = "월별 매출", 
         subtitle = "(매출액 단위: 백만원)") +
    geom_line(colour = "#1380A1", size = 1) +
    geom_hline(yintercept = 0, size = 1, colour="#333333")
```

csv 파일과 로고 이미지 파일

로고 이미지 파일은 img 폴더를 만든 후 그 안에 넣어주세요!

sp-logo.jpg
0.09MB
sales_data.csv
0.00MB

 

 

반응형

댓글