How to implement Gmail IMAP with Omniauth

徘徊边缘 提交于 2019-12-19 03:58:27

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/9084701/how-to-implement-gmail-imap-with-omniauth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!