Created
October 12, 2016 02:37
-
-
Save gecko655/42d17587780ddc1bfd4fc65b139472b6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "nkf" | |
require 'google/apis/gmail_v1' | |
require 'googleauth' | |
require 'googleauth/stores/file_token_store' | |
require 'rmail' | |
require 'fileutils' | |
class GmailMailer | |
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob' | |
APPLICATION_NAME = 'Gmail API Ruby Quickstart' | |
CLIENT_SECRETS_PATH = 'client_secret.json' | |
CREDENTIALS_PATH = File.join(Dir.home, '.credentials', | |
"gmail-ruby-quickstart.yaml") | |
SCOPE = Google::Apis::GmailV1::AUTH_SCOPE | |
MAIL_FROM_ALIAS = '[email protected]' | |
## | |
# 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 | |
FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH)) | |
client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH) | |
token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_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 | |
code = gets | |
credentials = authorizer.get_and_store_credentials_from_code( | |
user_id: user_id, code: code, base_url: OOB_URI) | |
end | |
credentials | |
end | |
def self.send(mail_to, mail_subject, mail_body) | |
# Initialize the API | |
service = Google::Apis::GmailV1::GmailService.new | |
service.client_options.application_name = APPLICATION_NAME | |
service.authorization = authorize() | |
message = RMail::Message.new | |
message.header['To'] = mail_to | |
message.header['From'] = MAIL_FROM_ALIAS | |
message.header['Subject'] = NKF.nkf('-WMjm0', mail_subject) | |
message.body = mail_body | |
service.send_user_message('me', | |
upload_source: StringIO.new(message.to_s), | |
content_type: 'message/rfc822') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment