As an exercise to write a program at the study session I am attending, there is a theme of sending an email with ruby, and the details of the exercise are described below.
By the way, it is a program sent from gmail that I usually use.
It was an issue while there was a time limit, so I hurriedly carried it out, but I was helped by having more references and libraries than I expected.
For authentication when sending an email from the app, instead of using the google account password as it is, authenticate using the app password issued in the google account settings. (Recommended method for security rather than using the password as it is)
From the above screen, select "Security"-> "App Password", select App: Email, Device (mac in my case), and then press the Generate button to display the App Password.
Thankfully, ruby has a gem for sending gmail, so I will use this.
gem install ruby-gmail
ruby-gmail gem seems to be interesting because it has various functions such as reading and editing received mails in addition to simply sending mails.
From the viewpoint of security, the gmail address and the application password obtained earlier will be set in the environment variable instead of being solidly written in the program, and will be obtained by the program.
export GMAIL_ID="The gmail address you want to send" export GMAIL_PASS="gmail app password"
Reflects the set environment variables.
This time, you can enter any destination address, subject, and body on the command.
require "gmail" USERNAME = ENV[ "GMAIL_ID" ] PASSWORD = ENV[ "GMAIL_PASS"] gmail = Gmail.new(USERNAME, PASSWORD) puts "Please enter the destination address" address_to = gets.chomp puts "Please enter a 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
I referred to this for most of the program. I am very grateful.
[[Ruby] Send Email with Gmail Account --TakBoy's Programming 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)