[Ruby] Send email from gmail with Ruby

1 minute read

Introduction

As an exercise to write a program at a study session in which I participate, there is a topic of sending an email with ruby, and the contents I implemented are described below.

By the way, it is a program that I send from gmail that I usually use.

It was an issue with a limited time, so I hurriedly implemented it, but I had more references and libraries than I thought, and it was helped.

Implementation environment, necessary items

  • OS :mac
  • ruby 2.6.6
  • Google account

Implementation procedure

Get Google App Password

Instead of using the google account password as it is for authentication when sending an email from the application, use the application password issued in the google account settings to perform authentication. (The recommended method for security rather than using the password as it is)

Account settings

From the above screen, select “Security” -> “App password”, then select the app: mail, device (mac in my case), and press the generate button to display the app password.

*As a prerequisite, it is necessary to enable two-step verification of the google account.

install ruby-gmail gem

Thankfully, ruby has a gem for sending gmail, so I will use that.

dcparker/ruby-gmail

gem install ruby-gmail

ruby-gmail gem has various functions such as reading and editing received mails in addition to simply sending mails.

Environment variable settings (gmail address, app password)

From the security point of view, the gmail address and the app password previously obtained are set in environment variables instead of solid writing in the program and will be obtained by the program.

export GMAIL_ID="gmail address you want to send"
export GMAIL_PASS="gmail app password"

Reflects the set environment variables.

source ~/.bash_profile

Creating an email sending program

This time, you can enter any destination address, subject, and text on the command.

require "gmail"

USERNAME = ENV[ "GMAIL_ID"]
PASSWORD = ENV[ "GMAIL_PASS"]

gmail = Gmail.new(USERNAME, PASSWORD)

puts "Please enter the recipient's address"
address_to = gets.chomp
puts "Please enter the subject"
title = gets.chomp
puts "Please enter the text"
text = gets

message =
  gmail.generate_message do
    to address_to
    subject title
    html_part do
      content_type "text/html; charset=UTF-8"
      body "<p>" + text + "</p>"
    end
  end

gmail.deliver(message)
gmail.logout

Reference article

Most of the programs are referred to here. I am very grateful.

[[Ruby] Sending email with Gmail account-TakBoy’s Programing Note](https://csharpmagazine.hatenablog.com/entry/2019/12/13/%E3%80%90Ruby%E3%80%91Gmail%E3%82%A2%E3%82%AB%E3%82%A6%E3%83%B3%E3%83%88%E3%81%A7%E3%83%A1%E3%83%BC%E3%83%AB%(E9%80%81%E4%BF%A1)