TMailで添付ファイル付きメールの送信

30分プログラム、その258。TMailを使って添付ファイル付きのメールを送信してみる。
実際のメールの送信はsendmailに任せるので、メールの内容を標準出力に出すだけ。

使い方

$ ruby attach-mail.rb | sendmail -t

ソースコード

#! /opt/local/bin/ruby -w
# -*- mode:ruby; coding:utf-8 -*-
#
# attach-mail.rb -
#
# Copyright(C) 2008 by mzp
# Author: MIZUNO Hiroki / mzpppp at gmail dot com
# http://howdyworld.org
#
# Timestamp: 2008/03/04 22:50:26
#
# This program is free software; you can redistribute it and/or
# modify it under MIT Lincence.
#
require 'tmail'
require 'base64'

mail = TMail::Mail.new

# 基本情報
mail.from = 'from@example.com'
mail.to   = 'to@example.com'
mail.subject = 'Message from Ruby'
mail.date = Time.now
mail.mime_version = '1.0'

# 添付ファイル
attach = TMail::Mail.new
attach.body = Base64.encode64 File.read('foo.jpg')
attach.set_content_type 'image','jpg','name'=>file
attach.set_content_disposition 'attachment','filename'=>file
attach.transfer_encoding = 'base64'

# 添付
mail.parts.push attach

puts mail.encoded