如何使用 Omniauth 实现 Gmail IMAP [英] How to implement Gmail IMAP with Omniauth

查看:32
本文介绍了如何使用 Omniauth 实现 Gmail IMAP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了几个关于通过 XOAUTH 连接到 Google 的 Gmail 的绝望信息来源:http://code.google.com/apis/gmail/oauth/protocol.html#imap

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

我正在尝试使用实现 IMAP 的gmail"gem:https://github.com/nu7hatch/gmail

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

最后,省略处理身份验证:https://github.com/Yesware/omniauth-google

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

我实际上如何将这些代码结合在一起以使某些东西可用?请让我知道任何现实世界的实现,这里有一些连接到 Gmail 的示例:http://otherinbox.comhttp://goslice.com

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

推荐答案

我和你一样在使用现有的 gem 时遇到了麻烦,因为 Google 的 XOAUTH 现在已被弃用.您应该使用他们的新 XOAUTH2.

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

这是一个使用 Google 的 XOAUTH2 协议从 Google 获取电子邮件的工作示例.此示例使用 mailgmail_xoauth, omniauthomniauth-google-oauth2 宝石.

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.

您还需要在 Google 的 API 控制台 中注册您的应用,以便获取您的 API令牌.

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

这篇关于如何使用 Omniauth 实现 Gmail IMAP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆