Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send emails in Rails 3 using the recipient's locale?

How can I send mails in a mailer using the recipient's locale. I have the preferred locale for each user in the database. Notice this is different from the current locale (I18n.locale), as long as the current user doesn't have to be the recipient. So the difficult thing is to use the mailer in a different locale without changing I18n.locale:

def new_follower(user, follower)   @follower = follower   @user = user   mail :to=>@user.email end 

Using I18n.locale = @user.profile.locale before mail :to=>... would solve the mailer issue, but would change the behaviour in the rest of the thread.

like image 200
Jose Avatar asked Aug 22 '10 01:08

Jose


People also ask

How do I use SMTP in Ruby on Rails?

Go to the config folder of your emails project and open environment. rb file and add the following line at the bottom of this file. It tells ActionMailer that you want to use the SMTP server. You can also set it to be :sendmail if you are using a Unix-based operating system such as Mac OS X or Linux.

What is action mailer?

Applications use action mailer to send and receive emails in ROR using mailer classes and views. To send an email with the help of the action mailer, we can perform the following steps: We have to set up a mailer with rails generate mailer . We have to create the template for the email.

How do I view Mailers in Rails?

Mailer views are located in the app/views/name_of_mailer_class directory. The specific mailer view is known to the class because its name is the same as the mailer method. In our example from above, our mailer view for the welcome_email method will be in app/views/user_mailer/welcome_email. html.


2 Answers

I believe the best way to do this is with the great method I18n.with_locale, it allows you to temporarily change the I18n.locale inside a block, you can use it like this:

def new_follower(user, follower)   @follower = follower   @user = user   I18n.with_locale(@user.profile.locale) do     mail to: @user.email   end end 

And it'll change the locale just to send the email, immediately changing back after the block ends.

Source: http://www.rubydoc.info/docs/rails/2.3.8/I18n.with_locale

like image 130
Miguelgraz Avatar answered Oct 03 '22 06:10

Miguelgraz


This answer was a dirty hack that ignored I18n's with_locale method, which is in another answer. The original answer (which works but you shouldn't use it) is below.

Quick and dirty:

class SystemMailer < ActionMailer::Base   def new_follower(user, follower)     @follower = follower     @user = user     using_locale(@user.profile.locale){mail(:to=>@user.email)}   end    protected   def using_locale(locale, &block)     original_locale = I18n.locale     I18n.locale = locale     return_value = yield     I18n.locale = original_locale     return_value   end end 
like image 37
jimworm Avatar answered Oct 03 '22 08:10

jimworm