:smtp => Mail::SMTP
:file => Mail::FileDelivery
:sendmail => Mail::Sendmail
:test => Mail::TestMailer
# config/environments/development.rb
config.action_mailer.delivery_method = :letter_opener
ActionMailer::Base.add_delivery_method :ses, AWS::SES::Base,
:access_key_id => 'abc',
:secret_access_key => '123'
config.action_mailer.delivery_method = :ses
require 'mail'
class CustomSmtpDelivery < ::Mail::SMTP
# SMTP 配置
def initialize(values)
self.settings = {:address => "smtp.gmail.com",
:port => 587,
:domain => 'yourdomain',
:user_name => "gmail_username",
:password => "gmail_password",
:authentication => 'plain',
:enable_starttls_auto => true,
:openssl_verify_mode => nil
}.merge!(values)
end
# 或者,把 SMTP 配置放到配置文件里
def initialize(options = {})
self.settings = options
end
attr_accessor :settings
# 必须重新实现 deliver! 方法
def deliver!(mail)
# 把收箱人替换成指定的,这里功能类似拦截器
mail['to'] = "to@example.com"
mail['bcc'] = []
mail['cc'] = []
super(mail)
end
end
add_delivery_method :custom_smtp_delivery, CustomSmtpDelivery
# config/environments/development.rb
config.action_mailer.delivery_method = :custom_smtp_delivery
ActionMailer::Base.custom_smtp_delivery_settings = {
:address => "smtp.gmail.com",
:port => 587,
# ...
}
# 获取所有可用的 delivery_methods
class_attribute :delivery_methods
module ClassMethods
# 必须结合 delivery_method :test 使用,存放着已经 deliver 的邮件对象,测试的时候可用到它。
delegate :deliveries, :deliveries=, to: Mail::TestMailer
end