2025-10-15

ActionMailer で From に表示名をつける方法

ActionMailer でメール送信をする際、ApplicationMailer に次のように書く例はよく見かけると思います。

class ApplicationMailer < ActionMailer::Base
  default from: 'notifications@example.com'
end

これで、ApplicationMailer を継承した全てのメーラークラスにて notifications@example.com を送信元メールアドレスとすることができるようになります。

しかしながら、このままだと例えば Gmail で受信したメールの送信元を見ると notifications とだけ表示されます。

notificationsとだけ表示される
notificationsとだけ表示される

メールアドレスの @ より前のローカルパートが表示名として使われているようです。 ですが、本来であればここにはサービス名を表示したいはずです。どうやればできるでしょうか。

ActionMailer::Base#email_address_with_name

Rails であれば、このようなよくありそうな要求であれば機能が用意されているかなと思い調べてみたらやはりありました。

email_address_with_name というメソッドを使うだけで、メールクライアントに表示名を出すことができます。

先のサンプルコードであれば、以下のようにすると MyAppnotifications の代わりに表示されるようになります。

class ApplicationMailer < ActionMailer::Base
-  default from: 'notifications@example.com'
+  default from: email_address_with_name('notifications@example.com', 'MyApp')
end

少し深堀り

実際このメソッドがやっていることは "MyApp <notifications@example.com>" という文字列を生成しているだけです。

ApplicationMailer.new.email_address_with_name('notifications@example.com', 'MyApp')
# => "MyApp <notifications@example.com>"

つまり、以下のようにしても同じ結果が得られます。

class ApplicationMailer < ActionMailer::Base
-  default from: email_address_with_name('notifications@example.com', 'MyApp')
+  default from: 'MyApp <notifications@example.com>'
end

このフォーマットは、Rails や Gmail 独自のものではなく RFC 5322 (Internet Message Format) の 3.4 節「Address Specification」で定義されている標準仕様でした。

山括弧 <> やスペースにはちゃんと意味があるので、やはり自前で実装するよりは email_address_with_name を使っておいた方が安心できそうです。

h3pei's icon

h3pei

フリーランスのソフトウェアエンジニア。Ruby / Rails アプリケーションの開発が得意領域。設計・実装・運用まで含めてプロダクト開発が好きです。

MENTAでアプリケーション開発や学習の支援・伴走もしています。