使用代码发邮件

Using code to send email

Tool
R
Python
Author

Tony D

Published

March 31, 2025

A guide to sending emails programmatically using the blastula package in R, covering credential setup, email composition, and sending from Gmail and Outlook.

This document provides a comprehensive guide to sending emails programmatically using R and Python. For R, it focuses on the blastula package, covering the entire workflow from creating SMTP credentials for Gmail and Outlook to composing and sending emails. It also demonstrates how to render Quarto content directly into an email body. The Python section is a placeholder for future content.

Using R or Python to send email

Using R

Send email with {blastula}.Also update in to R handbook

load library

Code
library(blastula)
library(keyring)

Step 1 create smtp credentials

gmail

Code
create_smtp_creds_key(
  id = "gmail001_creds",
  provider = "gmail",
  user = "verykoala@gmail.com",
  overwrite = TRUE
  )

outlook

Code
# create_smtp_creds_key(
#   id = "outlook001_creds",
#   provider = "outlook",
#   user = "jcpartner@outlook.com",
#   overwrite = TRUE
#   )

create_smtp_creds_file(file = "ggnot_throwaway_creds",
                       user = "jcpartner@outlook.com",
                       provider = "outlook")
Code
#delete_credential_key("gmail001_creds")
Code
view_credential_keys()

Step 2 email content

Code
library(blastula)
msg=compose_email(
  body = md(
  "Hi there 👋,
  
  This is an email to let you now thatrunning job **finished**.

  Best,<br>
  Tony"
  )
)

msg

Step 3 send email

Code
msg %>% 
  smtp_send(
    from = 'verykoala@gmail.com',
    to = "jcflyingco@outlook.com",
    subject = "Testing the email function",
    credentials = creds_key(id = "gmail001_creds")
  )
Code
library(Microsoft365R)
outl <- get_personal_outlook()
Code
# list the most recent emails in your Inbox
#outl$list_emails()
Code
em <- outl$create_email(msg, subject="Hello", to="jcflyingco@outlook.com")
Code
em$send()

Step3 (option B) send email with quarto content

create email Rmd file(.quarto_email.Rmd):


Code
.quarto_email.Rmd
---
title: "Quarto Email"
output: blastula::blastula_email 
---



# tesing

testing


# Reference:
https://www.youtube.com/watch?v=PihKq1GPlcc

create email

Code
email_obj=render_email('.quarto_email.Rmd')

View the email

Code
email_obj
Code
email_obj%>% 
  smtp_send(
    from = 'verykoala@gmail.com',
    to = "jcflyingco@outlook.com",
    subject = "Testing the email function",
    credentials = creds_key(id = "gmail001_creds")
  )
Code
em <- outl$create_email(email_obj, subject="Hello", to="jcflyingco@outlook.com")
em$send()

Using Python