You need to enable JavaScript to run this app. 如何在Rails应用中集成OAuth认证的Gmail API实现邮件发送
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rails应用中集成OAuth认证的Gmail API实现邮件发送

Rails 集成OAuth认证的Gmail API邮件发送实现(适配google-api-client ~> 0.34)

前置准备

  • 确认Gemfile已配置指定版本依赖:
gem 'google-api-client', '~> 0.34'
gem 'mail' # 用于构造标准MIME格式邮件

执行bundle install安装依赖

  • 将已下载的Google OAuth客户端密钥文件(默认名为client_secret.json)放置到项目config/目录下
  • 提前在Google Cloud控制台的OAuth配置中,把开发/生产环境的回调地址添加到允许的重定向URI列表,确保已启用Gmail API权限

授权流程实现

配置授权路由

在config/routes.rb中添加OAuth回调路由:

get '/auth/google' => 'google_auth#start'
get '/auth/google/callback' => 'google_auth#handle_callback'

实现授权控制器

新建app/controllers/google_auth_controller.rb,处理首次授权的跳转和凭证缓存:

require 'googleauth'
require 'google/apis/gmail_v1'

class GoogleAuthController < ApplicationController
  SCOPES = [Google::Apis::GmailV1::AUTH_GMAIL_SEND]
  CLIENT_SECRET_PATH = Rails.root.join('config/client_secret.json').to_s
  CREDENTIAL_STORE_PATH = Rails.root.join('config/gmail_user_credentials.yaml').to_s

  def start
    client_id = Google::Auth::ClientId.from_file(CLIENT_SECRET_PATH)
    token_store = Google::Auth::FileTokenStore.new(File.open(CREDENTIAL_STORE_PATH, 'w+'))
    authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPES, token_store)
    redirect_url = authorizer.get_authorization_url(base_url: "#{request.base_url}/auth/google/callback")
    redirect_to redirect_url
  end

  def handle_callback
    client_id = Google::Auth::ClientId.from_file(CLIENT_SECRET_PATH)
    token_store = Google::Auth::FileTokenStore.new(File.open(CREDENTIAL_STORE_PATH, 'w+'))
    authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPES, token_store)
    authorizer.get_credentials_from_code(
      user_id: 'default',
      code: params[:code],
      base_url: "#{request.base_url}/auth/google/callback"
    )
    render plain: "Gmail授权完成,可正常使用邮件发送功能"
  end
end

单用户自用场景可使用本地文件缓存授权凭证;多用户生产场景请将凭证存储对应用户的数据库字段,不要依赖本地文件存储。

封装Gmail发送服务

新建app/services/google_gmail_service.rb,封装服务初始化和邮件发送逻辑:

require 'google/apis/gmail_v1'
require 'googleauth'
require 'base64'
require 'mail'

class GoogleGmailService
  SCOPES = [Google::Apis::GmailV1::AUTH_GMAIL_SEND]
  CLIENT_SECRET_PATH = Rails.root.join('config/client_secret.json').to_s
  CREDENTIAL_STORE_PATH = Rails.root.join('config/gmail_user_credentials.yaml').to_s

  def initialize
    @gmail_service = Google::Apis::GmailV1::GmailService.new
    @gmail_service.client_options.application_name = '你的Rails应用名称'
    @gmail_service.authorization = load_cached_credentials
  end

  # 对外暴露的邮件发送方法
  def send(to:, subject:, content:, from: '完成授权的Gmail账号地址')
    mail = Mail.new do
      from from
      to to
      subject subject
      body content
    end
    # Gmail API要求传入URL安全的Base64编码的raw邮件内容
    encoded_mail = Base64.urlsafe_encode64(mail.to_s)
    message = Google::Apis::GmailV1::Message.new(raw: encoded_mail)
    # user_id设为me即代表使用当前授权的账号发送
    @gmail_service.send_user_message('me', message)
  end

  private

  def load_cached_credentials
    Google::Auth::UserRefreshCredentials.make_creds(
      json_key_io: File.open(CREDENTIAL_STORE_PATH),
      scope: SCOPES
    )
  end
end

常见问题规避

  • 不要将client_secret.json、凭证缓存文件提交到代码仓库,把对应路径添加到.gitignore,避免敏感凭证泄露
  • 未上线的测试应用需将测试使用的Google账号添加到OAuth同意屏幕的测试用户列表,否则会触发授权权限不足报错
  • 回调地址必须和Google控制台配置的URI完全一致,包括域名、端口、路径,否则会报重定向地址不匹配错误
  • 0.34版本的google-api-client已内置完整的Gmail V1接口封装,无需额外安装第三方Rails邮件gem,直接通过Google::Apis::GmailV1模块即可调用所有接口

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.20 00:54:03