LoginSignup
4
3

More than 5 years have passed since last update.

ruby-gmailでGmailの内容をslackに投稿する

Last updated at Posted at 2016-10-24

概要

  • ruby-gmailを使って、タイトルと本文をslackに投稿する
  • 投稿したメールは既読にする

slackのincoming webhook用URL取得

  • ネットで調べて取得しちゃいましょう

端末用パスワードの取得

https://security.google.com/settings/security/apppasswords
こちらのサイトで取得する

gem install

$ gem install ruby-mail

コード

# -*- coding:utf-8 -*-
require 'gmail'
require 'kconv'
require 'slack-notifier'

USERNAME = 'hoge@example.com' # gmailのアドレス
PASSWORD = '端末用パスワード'
WEBHOOK_URL = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxx'

def get_body(mail)
  if !mail.text_part && !mail.html_part
    return mail.body.decoded.encode("UTF-8", mail.charset)
  elsif mail.text_part
    return mail.text_part.decoded
  elsif mail.html_part
    return mail.html_part.decoded
  end
end

def send_slack(webhook_url, subject, body)
  notifier = Slack::Notifier.new webhook_url, channel: '#slack-channel', username: 'bot-name'
  notifier.ping "#{subject}\n```\n#{body}```"
end

def get_gmail_and_post_slack(mail_box)
  gmail = Gmail.new(USERNAME, PASSWORD)

  # utf8にデコードしてます。最後のmarkで既読にさせてます 
  gmail.mailbox(mail_box).emails(:unread).each do |email|
    mail_subject = email.subject.toutf8
    mail_body = get_body(email)
    send_slack(WEBHOOK_URL, mail_subject, mail_body)
    email.mark(:read)
  end

  gmail.disconnect
end

get_gmail_and_post_slack('gmailのbox名')

問題点

  • awsなどホスティングで動かしたかったが、Macじゃないと動かなかった。なぜだろう。
4
3
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
4
3