はじめに
Ruby Mailで添付ファイルを付ける方法ですが、検索してすぐに見つかる方法1だとエラーが発生してしまいましたが、それを解決しました。
環境はMail 2.7.1 です。
$ gem list mail
mail(2.7.1)
エラーになった方法
require 'mail' #gem install mail
mail = Mail.new do
from "from@example.com"
to "to@example.com"
subject "testmail"
body "Attachment mail test."
end
# この行がエラーになる。 This code is wrong. Error!
mail.add_file = "./attachment_file.txt"
# 以下省略
発生したエラーはundefined method `add_file='
です。
Did you mean? add_file
と言われました。
ということは、add_fileはメソッド、、、?
動作した方法
require 'mail' #gem install mail
mail = Mail.new do
from "from@example.com"
to "to@example.com"
subject "testmail"
body "Attachment mail test."
end
# これが正しい。This code is correct.
mail.add_file("./attachment_file.txt")
# 送信するところまで省略せずに記載
# 192.168.0.1にSMTPサーバがあると仮定
options = {
address: '192.168.0.1',
port: 25
}
mail.charset = 'utf-8'
mail.delivery_method(:smtp, options)
mail.deliver
いつから変更になったのか、はたまた元からメソッドが正しいのかは調べきれませんでしたが、少なくともMail 2.2.17の時点では、メソッドが正しかったようです。
https://www.rubydoc.info/gems/mail/2.2.17/Mail%2FMessage:add_file
検索結果を鵜呑みにせず、公式ドキュメントを確認するのは大事ですね。
-
執筆時点=2019/8/21では、2015年のQiita記事がトップヒットでした。 ↩