net-smpt xoauth2 でGmailを使って送信する。
GMail はアレコレややこしい。とりあえず、OAuth2に対応させれば、SMTPサーバーを使わせてもらえる。
require 'gmail_xoauth' require "googleauth" require "googleauth/stores/file_token_store" require 'gmail_xoauth' def client_access_token(user_id) client_secret_path = File.expand_path(File.dirname(__FILE__)+"/../../credentials/client_secret.json") token_path = File.expand_path(File.dirname(__FILE__)+"/../../credentials/tokens.yaml") scope = 'https://mail.google.com/' authorizer = Google::Auth::UserAuthorizer.new( Google::Auth::ClientId.from_file(client_secret_path), scope, Google::Auth::Stores::FileTokenStore.new(file: token_path) ) credentials = authorizer.get_credentials(user_id) credentials.refresh! credentials.access_token end def smtp_connect_by_xoauth() user="fax4783@morioka.biz" token=client_access_token(user) smtp = Net::SMTP.new("smtp.gmail.com", 587) smtp.enable_starttls_auto smtp.start('smtp.gmail.com', user, token, :xoauth2) smtp.finish puts 'OK' true end ret = smtp_connect_by_xoauth
client_secret や token は事前に発行しているという感じ
Gem の例
サンプルを作ったときに使ったGemfileの例
source "https://rubygems.org" git_source(:github) {|repo_name| "https://github.com/#{repo_name}" } gem "gserver" gem "net-smtp", '~>0.3.3' gem "mail", "~> 2.7" gem "google-apis-gmail_v1" gem "gmail_xoauth"
ここでのポイントは、"net-smtp", '~>0.3.3'
である。0.4.0
移行では"gmail_xoauth"
のauth の仕組みが変わってて動かないので注意。
関連資料
- https://takuya-1st.hatenablog.jp/entry/2022/03/14/175433
- https://takuya-1st.hatenablog.jp/entry/2022/03/14/181637