それマグで!

知識はカップより、マグでゆっくり頂きます。 takuya_1stのブログ

習慣に早くから配慮した者は、 おそらく人生の実りも大きい。

ruby を使ってメールを送る。Gmailで画像添付メールをお手軽に作成する(6行)

ruby を使ってメールを送る.Gmailアカウントを使ってメールを送りたいなと思った.

Evernoteに登録するときにコマンドラインからパパパパって送っちゃうのがいちばん手っ取り早い。Evernoteの同期処理やインポート処理は微妙だったので.

必要なもの

  • tmail
  • tlsmail
  • mime形式の知識 (添付ファイル送りたいなら知っときましょう)

メールを送るコード

  gmail = Gmail.new("your_gmail_or_google_apps_account","enter_password")   
  gmail.message = "this is a test from my class"
  gmail.to = "somebody@evernote.example.com"
  gmail.title ="test message"
  gmail.attach("http://www.google.co.jp/intl/en_com/images/srpr/logo1w.png") #Googleロゴを送る
  gmail.submit
  puts "END"


簡単ですねー。ファイルをURLも指定できる.「後で読む」が簡単になりました.

送ってみた


gmail クラス

require 'rubygems'
require 'tlsmail'
require 'tmail'
class Gmail
  attr_accessor :password, :username
  def initialize(username=nil,password=nil)
    @username,@password=username,password
    @mail = TMail::Mail.new
  end
  def message(message_string)
    @mail.body = message_string
  end
  def to(str)
    @mail.to = str
  end
  def title(str)
    @mail.subject = str
  end
  def submit()
    raise "enter a recipient e-mail address . use Gmail#to(str)" unless @mail.to
    @mail.date = Time.now
    Net::SMTP.enable_tls(OpenSSL::SSL::VERIFY_NONE)
    Net::SMTP.start("smtp.gmail.com", 587, "local", @username, @password, "plain" ){|smtp|
        smtp.sendmail(
        @mail.encoded,
        @mail.from,
        @mail.to )
    }
  end
  def attach_file(filename_or_uri)
    require 'mime/types'
    require 'open-uri'
    require 'base64'
    mime_type =  MIME::Types.of(filename_or_uri).pop
    attach = TMail::Mail.new
    attach.body = Base64.encode64 open(filename_or_uri).read
    attach.set_content_type mime_type.media_type, mime_type.sub_type,'name'=>filename_or_uri
    attach.set_content_disposition 'attachment','filename'=>filename_or_uri
    attach.transfer_encoding = 'base64'
    @mail.parts.push attach
    return
  end
  alias message= message
  alias title= title
  alias to= to
  alias attach attach_file
end

ポイントは tlsmail とtmail です。

作ってみて

Gmailで送るのはとても簡単だし,携帯(ガラケー)アドレスにも送ることが出来る.パソコンで見ていてパパッと転送するコマンドに利用しています。sendmailの代わりに send_gmailコマンド作って使ってる

send_gmail address title body attachments

みたいな感じでどんどんメールで投げてる.

メールってのは意外と便利。画像を投稿するのに、WEBAPIを調べなくても良い.はてなフォトライフTwitterやEvernoteなど、いろいろなところへ簡単に画像や添付ファイルをまとめてアップロード出来る。こういうの一つ作っておくととても応用の幅が広いレシピです.