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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With