3

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

And I'm trying the use the 'gmail' gem which implements IMAP: https://github.com/nu7hatch/gmail

Finally, ominauth for handling the authentication: https://github.com/Yesware/omniauth-google

How do I actually tie these codes together to make something usable? Please let me know of any real world implementations, here's some examples of connecting to Gmail: http://otherinbox.com http://goslice.com

hagope
  • 5,523
  • 7
  • 38
  • 52

1 Answers1

9

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
Andrew
  • 227,796
  • 193
  • 515
  • 708
  • This was really helpful thanks. I was using the "gmail" gem, and switching out to "gmail_xoauth" seemed to unstick the problem. Thanks. – stef Jun 11 '13 at 12:45
  • 1
    I don't think this solution works anymore. I keep getting: Net::IMAP::NoResponseError: Invalid credentials (Failure) – Richardsondx Aug 09 '15 at 15:46