Skip to content

Instantly share code, notes, and snippets.

@ysaito8015
Created June 15, 2020 02:10
Show Gist options
  • Save ysaito8015/82e3b47bbdadf792c866b252dc64c24a to your computer and use it in GitHub Desktop.
Save ysaito8015/82e3b47bbdadf792c866b252dc64c24a to your computer and use it in GitHub Desktop.
require "google/apis/gmail_v1"
require "googleauth"
require "googleauth/stores/file_token_store"
require "fileutils"
require "mail"
require "pry"
OOB_URI = "urn:ietf:wg:oauth:2.0:oob".freeze
APPLICATION_NAME = "Gmail API Ruby Mail Sender".freeze
CREDENTIALS_PATH = "credentials.json".freeze
# The file token.yaml stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
TOKEN_PATH = "token.yaml".freeze
SCOPE = Google::Apis::GmailV1::AUTH_GMAIL_SEND # grant access to send
##
# Ensure valid credentials, either by restoring from the saved credentials
# files or intitiating an OAuth2 authorization. If authorization is required,
# the user's default browser will be launched to approve the request.
#
# @return [Google::Auth::UserRefreshCredentials] OAuth2 credentials
def authorize
client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH
token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH
authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store
user_id = "default"
credentials = authorizer.get_credentials user_id
if credentials.nil?
url = authorizer.get_authorization_url base_url: OOB_URI
puts "Open the following URL in the browser and enter the " \
"resulting code after authorization:"
puts url
puts "Enter the authorization code:"
code = gets
credentials = authorizer.get_and_store_credentials_from_code(
user_id: user_id, code: code, base_url: OOB_URI
)
end
credentials
end
# Initialize the API
service = Google::Apis::GmailV1::GmailService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize
# create message
mail = Mail.new do
to "MAIL_ID_TO_WHOM_YOU_WANT_TO_SEND"
from "YOUR_MAIL_ID"
subject "Hello from ruby"
html_part do
content_type "text/html; charset=UTF-8"
body "This e-mail is sent from Gmail API via ruby. Isn't that Cool?"
end
end
service.send_user_message(
"me", upload_source: StringIO.new(mail.to_s),
content_type: "message/rfc822"
)
puts "Message Id: #{mail.message_id}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment