Skip to content

Instantly share code, notes, and snippets.

@koki-h
Last active August 29, 2015 14:26
Show Gist options
  • Select an option

  • Save koki-h/d234c836f49cdb492933 to your computer and use it in GitHub Desktop.

Select an option

Save koki-h/d234c836f49cdb492933 to your computer and use it in GitHub Desktop.
#sendmailコマンドで添付ファイル付きメールを送信。
#ruby1.8.5で最近のメールライブラリが動かなかったので。
require "base64"
def mail(to, attach_file)
now = Time.now
filename = "#{now.strftime("%Y%m%d-%H%M%S")}.csv"
mail_boundary = now.strftime("%Y%m%d%H%M%S")
mail = <<EOS
To: #{mail_address}
Subject: TEST MAIL
MIME-Version: 1.0
Content-type: multipart/mixed; boundary=#{mail_boundary}
Content-Transfer-Encoding: 7bit
--#{mail_boundary}
Content-type: text/plain; charset=iso-2022-jp
Content-Transfer-Encoding: 7bit
本文
--#{mail_boundary}
Content-type: text/comma-separated-values;
name=#{filename}
Content-Transfer-Encoding: base64
Content-Disposition : attachment;
filename=#{filename}
#{Base64.encode64(open(attach_file).read)}
--#{mail_boundary}--
EOS
#メールを一旦ファイルに保存。echoやprintfで直接文字列を出力しようとすると
#環境によってはエラーになる
mailfile = "/tmp/mail-#{$$}-#{now.strftime("%Y%m%d%H%M%S")}"
open(mailfile, "w") do |f|
f.write(mail)
end
system("cat #{mailfile} | /usr/sbin/sendmail -t")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment