1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Posted at

目的

  • 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: 'from@example.com',
  to: 'to@example.com',
  subject: 'TEST MAIL',
  body: "TEST MAIL #{Time.current}",
)

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

test_–IAM_と管理–.png
Admin_console.png

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?