2013-12-12 1 views
1

Rails 3.2 앱에서 배경 :, 나는 "무대"환경에서 조작 된 ActionMailer 구매 확인 이메일을 가지고있어서 지불 프로세서 샌드 박스 계정과 관련된 주소는 실제로 샌드 박스 계정을 관리하는 사람들의 전자 메일 주소로 전송됩니다. 아니, interceptor에 대한 좋은 유스 케이스처럼 보이는,Ruby on Rails Mail 인터셉터에서 이메일 주소를 바꾸는 것

# app/mailers/purchase_mailer.rb 
class PurchaseMailer < ActionMailer::Base 

    default :from => "\"#{SiteConfig.name}\" <#{SiteConfig.support_email}>" 

    def purchase_notification(purchase) 
    @purchase = purchase 

    mail :to => "\"#{purchase.customer_name}\" <#{address_filter(purchase.customer_email)}>", 
     :subject => "[#{SiteConfig.name}] Purchase Confirmation" 
    end 

    private 

    def address_filter(email_address) 
    # Check for and remove sandbox identifiers 
    if Rails.env.stage? 
     email_address.sub(/_\d+_p(er|re)@/, '@') 
    else 
     email_address 
    end 
    end 

end 

하지만, 헤이 : 이것은 현재 메일러 클래스 내에서 이루어집니다? 그래서 위의 address_filter 메소드를 뽑아서 Rails 애플리케이션에 추가했다.

# config/initializers/mail.rb 
Mail.register_interceptor(StageMailInterceptor) if Rails.env.stage? 

# lib/stage_mail_interceptor.rb 
class StageMailInterceptor 

    def self.delivering_email(message) 
    receivers = [] 
    message.to.each do |to| 
     receivers << to.sub(/_\d+_p(er|re)@/, '@') 
    end 
    message.to = receivers 
    end 
end 

언뜻보기에 이것은 잘 작동하는 것 같습니다. 무대 환경에서는 전자 메일이 도청되고 "받는 사람"주소가 전자 메일을 보내려는 전자 메일 주소가됩니다. 구매에 사용 된 샌드 박스 계정을 관리하는 사람이 전자 메일을받습니다. 모래 상자 계정의 이름이 사라진 것을 제외하고는 ... 완벽합니다. 이전에 "Joe Example" <[email protected]>"Joe Example" <[email protected]>으로 변경 한 내용이 이제 [email protected]

...으로 변경되었습니다. 이름이 사라졌습니다.

Mail message interface을 보면, message.to=은 이름으로 설정 될 수 있지만 message.to을 호출하면 이름이 제공되었는지 여부에 상관없이 이름이없는 이메일 주소의 배열을 가져옵니다.

질문 : 질문 : 메일 차단기에서 이메일 주소와 관련된 이름을 변경하지 않고 이메일 주소를 변경하는 올바른 방법은 무엇입니까?

답변

0

이것은 올바른 방법이 아닌 것처럼 보이지만 메시지의 "받는 사람"헤더를 가져와 교체하고 message.to=으로 설정하면 전자 메일 주소를 변경하는 동안 이름을 유지할 수 있습니다 . 따라서 나의 인터셉터는 다음과 같이되었습니다 :

# lib/stage_mail_interceptor.rb 
class StageMailInterceptor 

    def self.delivering_email(message) 
    message.to = message.header["To"].to_s.gsub(/_\d+_p(er|re)@/, '@') 
    end 

end