Skip to content

Instantly share code, notes, and snippets.

@te2u
Last active December 16, 2015 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save te2u/5506821 to your computer and use it in GitHub Desktop.
Save te2u/5506821 to your computer and use it in GitHub Desktop.
rubyを使った未読メール取得のサンプル(IMAP)
#!/usr/bin/ruby -Ku
require 'net/imap'
require 'kconv'
# imapのsslを有効にする
imap_usessl = true
imap_host = 'imap.example.com'
# ssl有効なら993、そうでなければ143
imap_port = 993
# imapのユーザ名とパスワード
imap_user = 'username'
imap_passwd = 'password'
# 未読(UNSEEN)のみ取得する
search_criterias = ['UNSEEN']
# メールヘッダの件名(Subject)
subject_attr_name = 'BODY[HEADER.FIELDS (SUBJECT)]'
# メール本文
body_attr_name = 'BODY[TEXT]'
# 接続
imap = Net::IMAP.new(imap_host, imap_port, imap_usessl)
# ログイン
imap.login(imap_user, imap_passwd)
# 対象のメールボックスを選択
imap.examine('INBOX')
# 未読メールを検索
imap.search(search_criterias).each do |msg_id|
# 未読メールの件名と本文を取得
msg = imap.fetch(msg_id, [subject_attr_name, body_attr_name]).first
subject = msg.attr[subject_attr_name].toutf8.strip
body = msg.attr[body_attr_name].toutf8.strip
# 何らかの処理を行う
# 当該メールを既読(Seen)にする
imap.store(msg_id, '+FLAGS', :Seen)
end
imap.logout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment