LoginSignup
1
1

More than 3 years have passed since last update.

Ruby Mailで添付ファイルを付ける方法(副題:検索上位が正しいとは限らない)

Last updated at Posted at 2019-08-21

はじめに

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

検索結果を鵜呑みにせず、公式ドキュメントを確認するのは大事ですね。


  1. 執筆時点=2019/8/21では、2015年のQiita記事がトップヒットでした。 

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1