LoginSignup
1
3

More than 3 years have passed since last update.

Ruby でメールの受信

Last updated at Posted at 2017-11-27

Ruby で imap サーバーからメールを受信する方法です。

imap_get.rb
#! /usr/bin/ruby
# -*- coding: utf-8 -*-
#
#   imap_get.rb
#
#                   Nov/27/2017
#
# ---------------------------------------------------------------------
require 'net/imap'
require 'kconv'

STDERR.puts "*** 開始 ***"
# imapのsslを有効にする
imap_usessl = true

imap_host = 'imap.mail.yahoo.co.jp'
imap_port = 993

# imapのユーザ名とパスワード
imap_user = 'xxxxxx'
imap_passwd = 'yyyyyy'

search_criterias = ['ALL']

# メールヘッダの件名(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

    envelope = imap.fetch(msg_id, "ENVELOPE")[0].attr["ENVELOPE"]
    puts "Name: #{envelope.from[0].name}"
    puts "From: #{envelope.from[0].mailbox}@#{envelope.from[0].host}"
    puts subject
    puts body
    puts
end

imap.logout

puts    "*** 終了 ***"
# ---------------------------------------------------------------------

次の環境で動作を確認しました。

$ uname -a
Linux iwata 5.4.0-42-generic #46-Ubuntu SMP Fri Jul 10 00:24:02 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

$ ruby --version
ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-linux-gnu]
1
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
1
3