app/mailers/heya/campaign_mailer.rb in heya-0.6.1 vs app/mailers/heya/campaign_mailer.rb in heya-0.7.0

- old
+ new

@@ -1,9 +1,10 @@ module Heya class CampaignMailer < ApplicationMailer DEFAULT_LAYOUT = "heya/campaign_mailer" layout -> { params.fetch(:step).params.fetch("layout", DEFAULT_LAYOUT) } + include Rails.application.routes.url_helpers def build user = params.fetch(:user) step = params.fetch(:step) @@ -24,11 +25,11 @@ mail( from: from, bcc: bcc, reply_to: reply_to, - to: user.email, + to: to_address(user, step), subject: subject, template_path: "heya/campaign_mailer/#{campaign_name}", template_name: step_name ) end @@ -49,8 +50,30 @@ super | ["heya/campaign_mailer/#{campaign_name}"] else super end end + end + + def to_address(user, step) + return step.params["to"].call(user) if step.params["to"].respond_to?(:call) + + if user.respond_to?(:first_name) + self.class.email_address_with_name(user.email, user.first_name) + elsif user.respond_to?(:name) + self.class.email_address_with_name(user.email, user.name) + else + user.email + end + end + + # This method is a backport and can be removed when we drop support of + # Rails 6.0; As of Rails 6.1, ActionMailer::Base, which we inherit from, + # already includes it. + def self.email_address_with_name(address, name) + Mail::Address.new.tap do |builder| + builder.address = address + builder.display_name = name + end.to_s end end end