How to implement Gmail IMAP with Omniauth

前端 未结 1 1264
生来不讨喜
生来不讨喜 2021-01-06 14:07

I\'ve read through several desperate sources of information on connecting to Google\'s Gmail through XOAUTH: http://code.google.com/apis/gmail/oauth/protocol.html#imap

1条回答
  •  不要未来只要你来
    2021-01-06 14:47

    I had trouble, like you, using existing gems since Google's XOAUTH is now deprecated. You should use their new XOAUTH2.

    Here is a working example of fetching email from Google using their XOAUTH2 protocol. This example uses the mail, gmail_xoauth, omniauth, and omniauth-google-oauth2 gems.

    You will also need to register your app in Google's API console in order to get your API tokens.

    # in an initializer:
    ENV['GOOGLE_KEY'] = 'yourkey'
    ENV['GOOGLE_SECRET'] = 'yoursecret'
    Rails.application.config.middleware.use OmniAuth::Builder do
      provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], {
        scope: 'https://mail.google.com/,https://www.googleapis.com/auth/userinfo.email'
      }
    
    end
    
    # in your script
    email = auth_hash[:info][:email]
    access_token = auth_hash[:credentials][:token]
    
    imap = Net::IMAP.new('imap.gmail.com', 993, usessl = true, certs = nil, verify = false)
    imap.authenticate('XOAUTH2', email, access_token)
    imap.select('INBOX')
    imap.search(['ALL']).each do |message_id|
    
        msg = imap.fetch(message_id,'RFC822')[0].attr['RFC822']
        mail = Mail.read_from_string msg
    
        puts mail.subject
        puts mail.text_part.body.to_s
        puts mail.html_part.body.to_s
    
    end
    

    0 讨论(0)
提交回复
热议问题