Skip to content

Instantly share code, notes, and snippets.

@walkure
Created May 25, 2021 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walkure/002a6077b94574bca6cb042300c0918a to your computer and use it in GitHub Desktop.
Save walkure/002a6077b94574bca6cb042300c0918a to your computer and use it in GitHub Desktop.
XOAUTH2対応のIMAP転送スクリプト
#!/usr/bin/ruby
require 'net/imap'
require 'oauth2'
IMAP_SERV = 'imap.gmail.com'
IMAP_PORT = 993
IMAP_SSL = true
folder = ARGV[0] || 'INBOX'
user = 'GMailアドレス'
pass = "XOAuth2 Refresh Token"
client_id = 'OAuth2 ID'
client_secret = 'OAuth2 Secret'
# IMAP XOAuth2 Authenticator
# cf.
# https://developers.google.com/gmail/imap/xoauth2-protocol
# https://github.com/google/gmail-oauth2-tools/wiki/OAuth2DotPyRunThrough
class XOAuth2Authenticator
def self.set_client(client_id,client_secret)
@@client_id = client_id
@@client_secret = client_secret
end
def process(data)
access_token = @client.get_token(:refresh_token => @refresh_token, :redirect_uri => 'urn:ietf:wg:oauth:2.0:oob', :grant_type=>'refresh_token')
# MEMO: Document requires base64 encoded string. And net/imap/authenticate send message with pack("m0").
"user=#{@user}\1auth=Bearer #{access_token.token}\1\1"
end
private
def initialize(user, refresh_token)
@user = user
@refresh_token = refresh_token
@client = OAuth2::Client.new(@@client_id,@@client_secret,
:site => 'https://accounts.google.com',:authorize_url=>'/o/oauth2/auth',:token_url=>'/o/oauth2/token')
end
end
XOAuth2Authenticator.set_client(client_id,client_secret)
Net::IMAP.add_authenticator('XOAUTH2', XOAuth2Authenticator)
begin
imap = Net::IMAP.new(IMAP_SERV, IMAP_PORT, IMAP_SSL)
imap.authenticate('xoauth2',user, pass)
begin
imap.examine(folder)
rescue
if folder =~ /[^\w]/ then
folder = Net::IMAP.encode_utf7(folder)
end
imap.create(folder)
end
rawmail = ''
STDIN.each { |l|
rawmail << l
}
if rawmail.gsub(/[\n|\r]+/, '').length == 0 then raise 'NO data input.' end
imap.append(folder, rawmail, nil, Time.now)
imap.logout
rescue => err
puts err.to_s
imap.logout
exit 1;
end
exit 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment