Emailing multiple users using ActionMailer - ruby-on-rails

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

Related

How to pass locale to ActiveJob / SuckerPunch when sending delayed email?

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

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.

Devise email confirmation not working on Heroku

When I click on the link in my confirmation email that devise sends, it seems to go to a path that is not recognized by my application.
The url looks something like this:
http://glowing-flower-855.heroku.com/users/confirmation?confirmation_token=lIUuOINyxfTW3TBPPI
which looks correct, but it seems to go to my 500.html file.
It has something to do with this code in my user model that overrides Devise's confirm! method:
def confirm!
UserMailer.welcome_message(self).deliver
super
end
According to my logs, this is the error:
2011-06-10T03:48:11+00:00 app[web.1]: ArgumentError (A sender (Return-Path, Sender or From) required to send a message):
2011-06-10T03:48:11+00:00 app[web.1]: app/models/user.rb:52:in `confirm!'
which points to this line: UserMailer.welcome_message(self).deliver
Here's my user mailer class:
class UserMailer < ActionMailer::Base
def welcome_message(user)
#user = user
mail(:to => user.email, :subject => "Welcome to DreamStill")
end
end
You are missing the "from:" value, it's a must for SMTP handling:
class UserMailer < ActionMailer::Base
# Option 1
#default_from "bob#dylan.com"
def welcome_message(user)
#user = user
mail(
# Option 2
:from => "paul#mccarthy.com",
:to => user.email,
:subject => "Welcome to DreamStill"
)
end
end

How can I use from names in ActionMailer? [Rails 2.3.5]

I want to show a pretty name in the e-mail clients
This should do the trick!
class UserMailer < ActionMailer::Base
def welcome_email(user)
recipients user.email
# PRETTY NAMES
from "Prettiest Pony <prettypony#imaginarium.tld>"
subject "Welcome to My Awesome Site"
sent_on Time.now
body {:user => user, :url => "http://example.com/login"}
end
end
See ActionMailer basics for more information

Resources