Направляющие ActionMailer с несколькими серверами SMTP

Это невозможно. Вы получаете дублирующее исключение.

Это также далеко не оптимально с такими данными конфигурации, как это в ваших классах реализации.

Если вы хотите использовать аннотации, вы можете настроить свой класс с помощью Конфигурация Java :

@Configuration
public class PersonConfig {

    @Bean
    public Person personOne() {
        return new Person("Joe", "Smith");
    }

    @Bean
    public Person personTwo() {
        return new Person("Mary", "Williams");
    }
}

31
задан mikej 13 October 2009 в 12:33
поделиться

8 ответов

class UserMailer < ActionMailer::Base
  def welcome_email(user, company)
    @user = user
    @url  = user_url(@user)
    delivery_options = { user_name: company.smtp_user,
                         password: company.smtp_password,
                         address: company.smtp_host }
    mail(to: @user.email,
         subject: "Please see the Terms and Conditions attached",
         delivery_method_options: delivery_options)
  end
end

Rails 4 допускает динамические варианты доставки. Приведенный выше код взят из руководства по основам действий, которое вы можете найти здесь: http://guides.rubyonrails.org/v4.0/action_mailer_basics.html#sending-emails-with-dynamic-delivery-options

Таким образом, можно иметь разные настройки smtp для каждого отправляемого вами сообщения электронной почты или, как в вашем случае использования для различных подклассов, таких как UserMailer, OtherMailer и т. Д.

15
ответ дан wnm 11 October 2019 в 11:35
поделиться

Решение для Rails 4.2 +:

config / secrets.yml :

production:
  gmail_smtp:
    :authentication: "plain"
    :address: "smtp.gmail.com"
    :port: 587
    :domain: "zzz.com"
    :user_name: "zzz@zzz.com"
    :password: "zzz"
    :enable_starttls_auto: true
  mandrill_smtp:
    :authentication: "plain"
    :address: "smtp.mandrillapp.com"
    :port: 587
    :domain: "zzz.com"
    :user_name: "zzz@zzz.com"
    :password: "zzz"
    :enable_starttls_auto: true
  mailgun_smtp:
    :authentication: "plain"
    :address: "smtp.mailgun.org"
    :port: 587
    :domain: "zzz.com"
    :user_name: "zzz@zzz.com"
    :password: "zzz"
    :enable_starttls_auto: true

config / environment / production.rb :

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = Rails.application.secrets.gmail_smtp

app / mailers / application_mailer.rb :

class ApplicationMailer < ActionMailer::Base
  default from: '"ZZZ" <zzz@zzz.com>'

  private

  def gmail_delivery
    mail.delivery_method.settings = Rails.application.secrets.gmail_smtp
  end

  def mandrill_delivery
    mail.delivery_method.settings = Rails.application.secrets.mandrill_smtp
  end

  def mailgun_delivery
    mail.delivery_method.settings = Rails.application.secrets.mailgun_smtp
  end
end

app / mailers / user_mailer.rb :

class UserMailer < ApplicationMailer
  # after_action :gmail_delivery, only: [:notify_user]
  after_action :mandrill_delivery, only: [:newsletter]
  after_action :mailgun_delivery, only: [:newsletter2]

  def newsletter(user_id); '...' end # this will be sent through mandrill smtp
  def newsletter2(user_id); '...' end # this will be sent through mailgun smtp
  def notify_user(user_id); '...' end # this will be sent through gmail smtp
end
11
ответ дан Mayur Shah 11 October 2019 в 11:35
поделиться

Рельсы-2.3. *

# app/models/user_mailer.rb
class UserMailer < ActionMailer::Base
  def self.smtp_settings
    USER_MAILER_SMTP_SETTINGS
  end

  def spam(user)
    recipients user.mail
    from 'spam@example.com'
    subject 'Enlarge whatever!'
    body :user => user
    content_type 'text/html'
  end
end

# config/environment.rb
ActionMailer::Base.smtp_settings = standard_smtp_settings
USER_MAILER_SMTP_SETTINGS = user_smtp_settings

# From console or whatever...
UserMailer.deliver_spam(user)
2
ответ дан Kostia 11 October 2019 в 11:35
поделиться

Боюсь, это не выполнимо изначально.
Но вы можете немного обмануть это, изменив переменную @@ smtp_settings в модели.

На Oreilly есть статья, которая объясняет это довольно хорошо, хотя их код не совсем чистый. http://broadcast.oreilly.com/2009/03/using-multiple-smtp-accounts-w.html

0
ответ дан Damien MATHIEU 11 October 2019 в 11:35
поделиться

https://github.com/AnthonyCaliendo/action_mailer_callbacks

Я обнаружил, что этот плагин довольно легко помог мне решить проблему (как за < 5 минут). Я просто изменяю @@ smtp_settings для конкретного почтовика в before_deliver, а затем меняю его обратно на значения по умолчанию в after_deliver. Используя этот подход, мне нужно только добавить обратные вызовы к почтовым программам, которым требуется @@ smtp_settings, отличный от значения по умолчанию.

class CustomMailer < ActionMailer::Base

  before_deliver do |mail|
    self.smtp_settings = custom_settings
  end

  after_deliver do |mail|
    self.smtp_settings = default_settings
  end

  def some_message
    subject "blah"
    recipients "blah@blah.com"
    from "ruby.ninja@ninjaness.com"
    body "You can haz Ninja rb skillz!"
    attachment some_doc
  end

end
0
ответ дан bkidd 11 October 2019 в 11:35
поделиться

Вот еще одно решение, которое, хотя и выглядит нелепо, но, я думаю, немного чище и его проще использовать в разных классах AM :: Base:

    module FTTUtilities
      module ActionMailer
        module ClassMethods
          def smtp_settings
            dict = YAML.load_file(RAILS_ROOT + "/config/custom_mailers.yml")[self.name.underscore]
            @custom_smtp_settings ||= HashWithIndifferentAccess.new(dict)
          end
        end

        module InstanceMethods
          def smtp_settings
            self.class.smtp_settings
          end
        end
      end
    end

пример Mailer:

    class CustomMailer < ActionMailer::Base
        extend FTTUtilites::ActionMailer::ClassMethods
        include FTTUtilites::ActionMailer::InstanceMethods
    end
0
ответ дан narsk 11 October 2019 в 11:35
поделиться

Решение для Rails 3.2:

class SomeMailer < ActionMailer::Base

  include AbstractController::Callbacks
  after_filter :set_delivery_options

  private
  def set_delivery_options
    settings = {
      :address => 'smtp.server',
      :port => 587,
      :domain => 'your_domain',
      :user_name => 'smtp_username',
      :password => 'smtp_password',
      :authentication => 'PLAIN' # or something
    }

    message.delivery_method.settings.merge!(settings)
  end
end

Решение, вдохновленное Как отправлять электронные письма с несколькими динамическими протоколами SMTP, используя Actionmailer / Ruby on Rails

0
ответ дан Community 11 October 2019 в 11:35
поделиться

На основании статьи Oreilly я придумал решение, о котором писал здесь: http://transfs.com/devblog/2009/12/03/custom-smtp-settings-for-a-specific-actionmailer-subclass

Вот соответствующий код:

class MailerWithCustomSmtp < ActionMailer::Base
  SMTP_SETTINGS = {
    :address => "smtp.gmail.com",
    :port => 587,
    :authentication => :plain,
    :user_name => "custom_account@transfs.com",
    :password => 'password',
  }

  def awesome_email(bidder, options={})
     with_custom_smtp_settings do
        subject       'Awesome Email D00D!'
        recipients    'someone@test.com'
        from          'custom_reply_to@transfs.com'
        body          'Hope this works...'
     end
  end

  # Override the deliver! method so that we can reset our custom smtp server settings
  def deliver!(mail = @mail)
    out = super
    reset_smtp_settings if @_temp_smtp_settings
    out
  end

  private

  def with_custom_smtp_settings(&block)
    @_temp_smtp_settings = @@smtp_settings
    @@smtp_settings = SMTP_SETTINGS
    yield
  end

  def reset_smtp_settings
    @@smtp_settings = @_temp_smtp_settings
    @_temp_smtp_settings = nil
  end
end
21
ответ дан 27 November 2019 в 22:01
поделиться
Другие вопросы по тегам:

Похожие вопросы: