Gmail api を ServiceAccount ( G Suite 管理下の ) で行うのは大変


目的

  • Gmail API でのメール送信
  • G suite 管理下のドメイン配下からの送信
  • ユーザーのトークンでは無くて ServiceAccount 経由

必要な事

  • サービスアカウントの詳細で、「G suite ドメイン全体の委任を有功にする」
  • G suite管理画面より、Api scopes を設定する( 不明瞭な点あり

Api scopes

http://www.google.com/m8/feeds/contacts/,http://www.google.com/m8/feeds/groups/,https://mail.google.com/

( なんでか判らないけど、mail.google.com スコープだけだと権限エラーになってしまうので、この三つのスコープが必須

sample code ( ruby

# frozen_string_literal: true

class GmailDeliveryMethod
  attr_reader :settings

  def initialize(settings)
    @settings = settings
  end

  def deliver(mail)
    credentials = Google::Auth::ServiceAccountCredentials.new(
      token_credential_uri: settings[:token_uri],
      audience: settings[:token_uri],
      scope: Google::Apis::GmailV1::AUTH_SCOPE,
      issuer: settings[:client_email],
      signing_key: OpenSSL::PKey::RSA.new(settings[:private_key]),
      project_id: settings[:project_id],
    )
    credentials.sub = mail.from.first
    gmail = Google::Apis::GmailV1::GmailService.new
    gmail.authorization = credentials
    gmail.send_user_message(
      mail.from.first,
      upload_source: StringIO.new(mail.to_s),
      content_type: 'message/rfc822',
    )
  end
  alias deliver! deliver
end


message = Mail.new(
  from: '[email protected]',
  to: '[email protected]',
  subject: 'TEST MAIL',
  body: "TEST MAIL #{Time.current}",
)

GmailDeliveryMethod.new({...}).deliver(message)