Shoken Startup Blog

KitchHike Founder/CTO

ruby-gmailを使ってRubyからGmailの添付ファイルを取得

ruby-gmailを使ってRubyからGmailのメールを受信して本文を取得 - Shoken OpenSource Society
これの続きです。

前回に引き続き、ruby-gmailを使ってRubyからGmailからメールを取得します。
今回は添付ファイルの扱いです。

環境

OS CentOS 5.4
ruby 1.9.3
gem 1.8.21
ruby-gmail 0.2.1
mail 2.4.4

実装

ruby-gmailはmikel/mailのラッパーなので、mikel/mailのドキュメントを読みます。
mikel/mail · GitHub

Testing and extracting attachmentsという項目にサンプルコードが書いてあります。

mail.attachments.each do | attachment |
  # Attachments is an AttachmentsList object containing a
  # number of Part objects
  if (attachment.content_type.start_with?('image/'))
    # extracting images for example...
    filename = attachment.filename
    begin
      File.open(images_dir + filename, "w+b", 0644) {|f| f.write attachment.body.decoded}
    rescue Exception => e
      puts "Unable to save data for #{filename} because #{e.message}"
    end
  end
end

上記を前回のソースにマージ。
添付ファイルが画像ファイルだったら/tmp/以下に保存するコードです。

#coding: utf-8
require 'gmail'

USERNAME='' #gmailのアドレス
PASSWORD='' #gmailのパスワード
images_dir='/tmp/'

gmail = Gmail.new(USERNAME,PASSWORD)

mails =  gmail.inbox.emails(:all).map do |mail| #emailsの引数には:all,:read,:unreadがある
  #件名、日付、From、To
  puts "Subject: #{mail.subject}"
  puts "Date: #{mail.date}"
  puts "From: #{mail.from}"
  puts "To: #{mail.to}"

  #本文処理
  if !mail.text_part && !mail.html_part
    puts "body: " + mail.body.decoded.encode("UTF-8", mail.charset)
  elsif mail.text_part
    puts "text: " + mail.text_part.decoded
  elsif mail.html_part
    puts "html: " + mail.html_part.decoded
  end

  #添付ファイル処理
  mail.attachments.each do | attachment |
    # Attachments は添付ファイルのリストのオブジェクト
    if (attachment.content_type.start_with?('image/'))
      # 添付ファイルが画像ファイルだった場合の処理
      filename = attachment.filename
      begin
        File.open(images_dir + filename, "w+b", 0644) {|f| f.write attachment.body.decoded}
      rescue Exception => e
        puts "Unable to save data for #{filename} because #{e.message}"
      end
    end
  end
end

gmail.disconnect