Mails sent from within rake tasks are not sanitized.
- Install sanitize_email.
- Configure it in your application, see below.
- Invoke: RAILS_ENV=development rake mail
- Observe mail is being delivered to real@address.com instead of adress@for.development.com.
in lib/tasks/mail.rake:
task :mail => :environment do
Mailer.deliver_my_mail 'real@address.com'
end
in config/initializers/sanitize_email.rb:
ActionMailer::Base.sanitized_recipients = "adress@for.development.com"
ActionMailer::Base.sanitized_bcc = nil
ActionMailer::Base.sanitized_cc = nil
ActionMailer::Base.local_environments = %w( development )
Workaround:
Use Mailer.force_sanitize = true
Hrmm...
Is it the case that the :environment rake task does not load initializers?. If you place your sanitize_email initialization code in a config.after_initialize block in config/environments/development.rb instead of in an initializer, that would probably also solve the problem.
I don't usually install sanitize_email on my production server, so in my projects I don't use an initializer (because then production would throw a runtime error when trying to set sanitized_receipients). As a result, I'm considering obsoleting ActionMailer::Base.local_environments and just having it always be active if it's been loaded.
Do you have any thoughts on this?
I've verified that :environment task loads initializers, but I've placed sanitize_email configuration in config/environments/development.rb as you suggested as this is probably better place. The results are the same. It is also interesting that putting "puts ActionMailer::Base.sanitized_recipients" in the rake task displays sanitized recipient, the same I've set in config. But sending email makes it go to the real address instead of sanitized one.
Ok cool, thanks for following up. It's probably a fairly quick fix. I hope to be able to get to it by tomorrow. Let me know if you have any other issues.
I'm using ARMailer gem, and it may be the source of trouble here. I've verified that using config.action_mailer.delivery_method = :test resolves the problem -- emails generated have correctly sanitized recipients. I need to investigate ARMailer + sanitize_email interaction...
Ahh, that could very well be the issue. Note that sanitize_email works at the envelope level. So the Tmail object that it creates will still have the unsanitized to: value on it, but ActionMailer will ignore that in the presence of sanitize_email.
So if ARMailer is reading the TMail object, then it's likely storing the unsanitized addresses in the database. And if the executable that actually clears out the ARMailer database table is not run in an environment that loads sanitize_email, then the original email would be used.
If you gather any notes on the combination of ARMailer and sanitize_email, please share them with me. I'd like to add them to the documentation so that others can avoid the pitfalls as well.
Let me know if I can help you further.