How to pass locale to ActiveJob / SuckerPunch when sending delayed email? - ruby-on-rails

In my Rails 5 app I am trying to send emails with ActiveJob and Sucker Punch:
# app/controllers/users_controller.rb
class UsersController < ApplicationController
def activate
user = User.find_by(:activation_token => params[:id])
user.activate
SendFollowUpEmailJob.perform_in(30, user)
sign_in user
end
end
# app/jobs/send_follow_up_email.rb
class SendFollowUpEmailJob < ActiveJob::Base
include SuckerPunch::Job
queue_as :default
def perform(user)
SupportMailer.follow_up(user).deliver_later
end
end
# app/mailers/support_mailer.rb
class SupportMailer < ApplicationMailer
layout nil
default :from => "admin#app.com"
def follow_up(user)
#user = user
mail :to => #user.email, :subject => t('.subject')
end
end
# app/views/user_mailer/activation.html.erb
<%= link_to(t('views.activate'), activate_user_url(#user.activation_token, :locale => "#{I18n.locale}")) %>
Everything works except that the email is always sent in the default locale rather than the locale that was passed into the activate action.
All emails throughout the application are always sent in the correct locale, so it must down to either ActiveJob or SuckerPunch.
If you can help, please let me know. Thanks.

I'm familiar with I18n within the application, but not so much in mailers. Remember that the mailer is being sent outside the request (ActiveJob), so it has no knowledge of anything that happened there. It looks like you haven't done anything to tell the mailer that it should be sending in a specific locale....
OK maybe this has the answer for you (and me!) https://niallburkley.com/blog/localize-rails-emails/
I18n.with_locale(#user.locale) do
mail(
to: #user.email,
subject: I18n.t('user_mailer.new_follower.subject')
)
end

Related

Sending Email Messages exposes the email addresses of every user to the recipients. How to fix?

I like to send mails such that my JobNotifier/Mailer iterates through the Subscriber's Email List and call deliver "n" times, if that could be the solution to my problem.
Unfortunately, all I have done sends Emails Messages and expose the email addresses of every user to the recipients, which is not suppose to be.
Here are my codes
create method right inside my jobs_controller.rb
def create
#job = Job.new(job_params)
if #job.save
# Deliver the Posted Job
JobNotifier.send_post_email(#job).deliver
redirect_to preview_job_path(#job)
else
render :new
end
end
app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
default to: Proc.new { User.pluck(:email).uniq },
from: 'FarFlungJobs <no-reply#farflungjobs.com>'
layout 'mailer'
end
app/mailers/job_notifier.rb
class JobNotifier < ApplicationMailer
def send_post_email(job)
#jobs = job
mail( :subject => 'New job posted on FarFlungJobs'
)
end
end
test/mailers/preview/job_notifier_preview.rb
# Preview all emails at http://localhost:3000/rails/mailers/job_notifier
class JobNotifierPreview < ActionMailer::Preview
def send_post_email
user = User.all
JobNotifier.send_post_email(user)
end
end
Tried to hop on my browser to test my Mailer using the URL shown below to preview/test my mailer:
http://localhost:3000/rails/mailers/job_notifier/send_post_email
Outcome of my test is this image below (at least if needed to help me with my problem):
Am using Rails
4.2.1
You have to send the email to each user separately. It will take much longer but it won't show other user's emails.
So in your controller, you will have something like this:
def create
#job = Job.new(job_params)
if #job.save
User.pluck(:email).uniq.each do |email|
# Deliver the Posted Job
JobNotifier.send_post_email(#job, email).deliver
end
redirect_to preview_job_path(#job)
else
render :new
end
end
Or you could put the loop inside the mailer
Edit:
You'll need to change your mailer to be able to handle extra argument:
class JobNotifier < ApplicationMailer
def send_post_email(job, email)
#jobs = job
mail(:to => email :subject => 'New job posted on FarFlungJobs')
end
end

Issue with ActionMailer Mandrill in Rails

I have a cab booking platform created in Rails. I am using the Mandrill smtp settings in production to send booking confirmation mails to users of my platform. Then I generated a mailer called user_mailer with the following code:
class UserMailer < ActionMailer::Base
default :from => "my_company_email"
def booking_confirmation(user)
#user = user
mail(:to => user.email, :subject => "Booking Confirmation")
end
end
Then I created booking_confirmation.html.erb page in user_mailer views with some generic content inside. Finally I called the user_mailer in one of my controllers as follows:
UserMailer.booking_confirmation(current_user).deliver
My problem is that when I want to include more details (such as Travel date, Travel time, etc.) within the mail delivered to my customer. I am trying this within my booking_confirmation.html.erb page: <%= #user.bookings.last.date %> to display the Travel Date to the customer. But this doesn't get displayed. Why is it so?
I would pass in the booking like
UserMailer.booking_confirmation(current_user, booking.id).deliver
then in the class UserMailer I would do
class UserMailer < ActionMailer::Base
default :from => "my_company_email"
def booking_confirmation(user, booking)
#user = user
#booking = Booking.find(booking)
mail(:to => user.email, :subject => "Booking Confirmation")
end
end
now on your erb you should have #booking.date to use
Its not a mandrill issue.something wrong with application code.
Check whether your following code has the date value present for last bookings.
#user.bookings.last.date

How to send mail for multiple models in rails

I am new to rails. I am having problem in mail sending to multiple models. Our project contains parent,teacher and student models.each module having number of users(student,parent,teacher). And also I am having three check box.that is student,teacher,parent.when I click student and teacher.the mail should be sent to all teachers and all students.
If I want send a mail to teacher and also student means ,the problem behind this, mail was sending only to teacher not student. how to solve this problem.and I included my coding.
Controller
def send_news_letter
if params[:announcement].present?
#announcement = Announcement.find(params[:announcement].keys).first
end
if params[:students].present? and params[:teachers].present?
#student = Student.pluck(:email)
#teacher = Teacher.pluck(:email)
UserMailer.send_multiple_email(#student,#teacher,#announcement).deliver
redirect_to announcements_url, :notice => "Newsletter Delivered Successfully" a
end
end
Usermailer.rb
class UserMailer < ActionMailer::Base
default to: Proc.new {Teacher.pluck(:email)},
to: Proc.new {Student.pluck(:email)},
from: "from#example.com"
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.user_mailer.password_reset.subject
#
def password_reset(user)
#user = user
mail :to => user.email, :subject => "Password Reset"
end
def send_multiple_email(user,employee,announcement)
#user = user
#employee = employee
#announcement = announcement
mail :subject => "Deliver"
end
end
Please help me.Thanks in advance.
First, in your controller I would store all addresses in one array:
#emails = []
if params[:students].present?
#emails += Student.pluck(:email)
end
if params[:teachers].present?
#emails += Teacher.pluck(:email)
end
if params[:parents].present?
#emails += Parent.pluck(:email)
end
UserMailer.send_multiple_email(#emails,#announcement).deliver
And then in your mailer change to this:
def send_multiple_email(emails,announcement)
#announcement = announcement
emails.each do | address |
mail :to => address, :subject => "Deliver"
end
end
Please note, that if you're referencing your models in the mailer template (such as "Hi <%= #user.name %>!") then you need to load the whole model object. Now you're just using pluck to get a list of all the addresses you want to send to. To get the whole model, change pluck(:email) to all in your controller and change your mailer to reference the attributes in that model instead. This also means your three models need to have the same attribute names (at least the ones you intend to use in the mailer).
Hope it makes sense.

Emailing multiple users using ActionMailer

This is a total newbie question, but I wonder if someone could assist with setting up a mailer. I have a model 'users' and nested underneath it a 'contacts' model, (with a has_many/belongs_to relationship).
I am now trying to create a mailer which will be triggered by a specific action (create post) on a user page, and will email all the contacts belonging to that user. But I can't crack the syntax required on the mailer - I've tried setting recipients to #user.contacts.all and I've tried looping through them as with this solution. Can anybody advise on the cleanest way to do it?
Here's the code I have so far:
Posts controller:
after_create :send_contact_email
private
def send_contact_email
ContactMailer.contact_email(self).deliver
end
contact_mailer (this is my latest attempt, taken from the RoR site - I suspect this is NOT the best way to do it...)
class ContactMailer < ActionMailer::Base
def contact_email(user)
recipients #user.contacts.all
from "My Awesome Site Notifications <notifications#example.com>"
subject "Welcome to My Awesome Site"
sent_on Time.now
body {}
end
end
And then a basic message for the contact_email.html.erb.
The current error is:
NoMethodError in UsersController#create_post
undefined method `contacts' for nil:NilClass.
Any advice you can offer would be really gratefully received!
* Update *
Following Baldrick's advice, the contact_email method is now:
class ContactMailer < ActionMailer::Base
default :to => Contact.all.map(&:contact_email),
:from => "notification#example.com"
def contact_email(user)
#user = user
mail(:subject => "Post added")
end
end
There's a typo: you are using #user instead of user in the contact_email method.
It may not be the only problem, but at least it's the cause of the error message "undefined method 'contacts' for nil:NilClass "
Update
So with the right syntax, remove the :to from default options, and set it in the contact_emailmethod, with the contacts of your user:
class ContactMailer < ActionMailer::Base
default :from => "notification#example.com"
def contact_email(user)
#user = user
mail(:subject => "Post added", :to => user.contacts.map(&:contact_email),)
end
end
class ContactMailer < ActionMailer::Base
default :to => Contact.all.map(&:contact_email),
:from => "notification#example.com"
def contact_email(user)
recipients = user.contacts.collect(&:contact_email).join(',')
mail(:subject => "Post added", :to => recipients)
end
end

Mailer result as String?

In our custom sales app our users are able to send emails based on text partials they choose. We need to record the sent mails in an activity model. How do I get the mailer result as a string in order to save it?
Instead of calling the deliver method to send the mail, you can capture the email message by calling to_s. For example, if you have a mailer:
class MyMailer < ActionMailer::Base
default :from => "sender#me.com"
def my_email
mail(:to => "destination#you.com", :subject => "Mail Subject")
end
end
you would do
mail_content = MyMailer.my_email.to_s
May be you can using a mail observer like in the following example :
class MailObserver
def self.delivered_email(message)
test = Activty.create do |activity|
# etc.
end
end
end
Find here

Resources