Issues Looping through an array in Active Mailer - ruby-on-rails

I am trying to implement a feature which allows user to send one email to multiple recipients. I split the recipient email params by calling the .split method which turns it into an array. Then I loop through the array with the each method which should apply the mail method to each element in the array. The controller and mailer code is given below.
controller code
def create
#scoreboard = Scoreboard.find(params[:scoreboard_id])
#invitation = #scoreboard.sent_invitations.build(invitation_params)
if #invitation.save
UserMailer.registered_invitation_email(#scoreboard, #invitation).deliver_now
flash[:success] = "Invitation sent successfully"
redirect_to new_scoreboard_invitation_path
else
render 'new'
end
end
end
mailer code
def registered_invitation_email(scoreboard, invitation)
#scoreboard = scoreboard
#invitation = invitation
split_email = #invitation.recipient_email.split
split_email.each do |email|
mail(to: email, subject: "View scoreboard")
end
end
The problem is that it only sends the email to the last element in the array. For example, if the user types in "joe#example.com Mike#example.com" in the form it will only send an email to the last element in an array. In this case, Mike#exapmle.com. I am not sure why that is. I think I am looping through it correctly. I am not sure what's causing the problem. I am not sure if its the loop or maybe loops don't work in active mailer. Not exactly sure. Any help would be appreciated. Thanks!!

Try something like this
Create a model with fields
field :mail_to
field :subject
create a method in the same model
def deliver
UserMailer.send_invitation_mail(self).deliver
end
Mailer
def send_invitation_mail(email)
mail(to: email.mail_to, subject: email.subject)
email.destroy
end
Controller
def create
user_emails.each do |email|
email = Email.new(:mail_to => "xxx#yyy.com",:subject => "View Scoreboard") # Email is the model name.
email.deliver
sleep(1)
end
end
This way u can also log and also deliver all mails together in the model and also do various manipulations on the email.

Related

Email notifications not working using rails

I will preface this saying that I know almost nothing about rails. But I am trying to fix this issue involving rails so any help would be greatly appreciated (and also, if you could dumb it down for me that would be great!)
We have a rails email notification set up for two of our sites. If a user fills out an application on our English site, then a notification email is sent to person A. If a user fills out an application on our French site, then a notification email is sent to person B.
However, at the moment it seems like all emails are going to person A regardless of whether an application is filled out on the English or French site. How can I fix this?
Here is the code from the admin_mailer.rb file:
class AdminMailer < ActionMailer::Base
default from: 'noreply#canwise.com'
def contact_email
#contact = Contact.last
mail to: 'email1#1test.com'
end
def application_email
#application = Application.last
mail to: 'email1#test.com'
end
def eps_contact_email
#contact = Contact.last
mail to: "email2#test.com"
end
def eps_application_email
#application = Application.last
mail to: 'email2#test.com'
end
def salesforce_application_failure(application)
subject = "Application #{application.id} submitted by #{application.firstName} #{application.lastName} failed to submit to salesforce."
mail(to: 'test#test.com', subject: subject) do |format|
format.text { render text: '' }
end
end
end
And here is the code from the application.rb file:
def email_notification
if provider == 'www.frenchsite.com'
AdminMailer.eps_application_email.deliver
else
AdminMailer.application_email.deliver
end
end
HELP PLEASE!
If the emails are all going to email1#test.com, then it only means that your provider for french is not matching 'www.frenchsite.com'. The 'if' statement is always resulting in false.

Rails 4 | Properly creating and saving in controller

I'm creating a messaging system of sorts. It's part of a bigger overall system in Rails 4.
Anyway, to setup my question briefly I have users who can both send and receive messages. So in my "new" users' view I send a parameter [:receiver_id] to the message controller when creating a new message.
My question is how do I get the #send_to variable down to the create action properly. I had to send it into the messages#new action via the receiver_id from the users' view. Do I store it as a message parameter somehow or make it a hidden parameter?
Here is my messages controller
class MessagesController < ApplicationController
def new
#message = Message.new
#this :receiver_id is being sent from the show view in the user controller / view
#it is being used to pass a parameter
#send_to = User.find(params[:receiver_id])
#message.sender = current_user
#message.receiver = #send_to
#the form_for should save the message with the RESTful action of create method in this controller
end
def create
debugger
#messasge = Message.create!(message_params)
redirect_to users_path
end
def index
#messages = current_user.messages
end
def sent
#messages = current_user.messages
end
def message_params
params.require(:message).permit!
end
end
I know from rails routing mostly about RESTful actions, and yes I have read over the routing guide again before writing this.
EDIT:
I have moved these two lines down into the create function. The #send_to needs the :receiver_id though.
#message.sender = current_user
#message.receiver = #send_to
You should implement an asynchronous request for sending messages, cause it might be annoying for system users to redirect to another page just to send a message. From the above snippets it is not known (the logic).
Having an asynchronous request, which would serve a dialog with new message form, next step is just to send form data to messages#create action. I assume that user, while fulfilling form data, can select somehow message recipient.
Action new does not need to know who is the message receiver.
Don't use Message.create! (with !) because it will raise an exception if creation fails. Use save instead and handle case if it would fail,
e.g:
def create
#message = Message.new params[:message]
#message.save
respond_to do |f|
f.json do
render :json => {:success => #message.persisted?, :message => #message}.to_json
end
end
end

Rails Actionmailer Sending Multiple Recipients

I'm having trouble getting Rails to send an email to multiple users at once. I am trying to send a notification to multiple venues signed up to my site when an Enquiry that matches them is approved.
A pending Enquiry has to be approved by admin. The mailer is passed the #enquiry, which is when the email is triggered. Shown here in my Enquiries controller:
def approve
#enquiry.approve
redirect_to [:admin, #enquiry], notice: 'Enquiry is approved.'
SupplierMailer.new_enquiry(#enquiry).deliver
end
In my Supplier_mailer.rb, I have this method:
def new_enquiry(enquiry)
#enquiry = enquiry
#enquiry.venues.each do |venue|
mail(to: venue.supplier.user.email, subject: 'You have a new enquiry')
end
end
Currently, it is only sending to 1 email address, so not looping properly.
Models:
Enquiry
has_and_belongs_to_many :venues
Supplier
has_many :venues
has_one :user
What have I done wrong?
Thanks
The new_enquiry method is supposed to build one email, which is then being send with deliver method. The loop work correctly, however every time you're calling mail, you override its previous call, and the method returns the last call.
Instead, first get the list of recipients, and use it as a to attribute
emails = #enquiry.venues.map {|venue| venue.supplier.user.email}
mail(to: emails, subject: 'You have a new enquiry')
If you are not happy with sending other emails to each other, you will need place Mailer action inside the loop:
def approve
#enquiry.approve
redirect_to [:admin, #enquiry], notice: 'Enquiry is approved.'
#enquiry.venues.each do |venue|
SupplierMailer.new_enquiry(#enquiry, venue).deliver
end
end
def new_enquiry(enquiry, venue)
#enquiry = enquiry
mail(to: venue.supplier.user.email, subject: 'You have a new enquiry')
end
Final option is pretty hacky, but provides best interface:
class SupplierMailer << ActionMailer::Base
def self.new_enquiry(enquiry)
#enquiry = enquiry
mails = #enquiry.venues.map do |venue|
mail(to: venue.supplier.user.email, subject: 'You have a new enquiry')
end
class << mails
def deliver
each(&:deliver)
end
end
mails
end

Displaying Action Mailer variable in view returns "nil"

I am trying to let a user submit a form that sends an email message to another user. Everything is working fine, except I am trying to store the body of the email in a variable to display in the view for the mailer and am getting 'nil'. I set up a user_mailer.rb:
class UserMailer < ActionMailer::Base
default :from => "myemail#gmail.com"
def message_user(user, recipient, subject, body)
#user = user
#recipient = recipient
#body = "#{body}"
mail(:to => "#{recipient.name} <#{recipient.email}>", :subject => "Reelify message: #{subject}" )
end
end
and here is my messages_controller.rb :
def new
#user = current_user
if !params[:receiver].blank? and !params[:subject].blank? and !params[:body].blank?
#recipient = User.find_by_name(params[:receiver])
UserMailer.message_user(#user, #recipient, params[:subject], params[:body]).deliver
flash[:notice] = "This flash means it should work.. #{#user.name} #{#recipient.name}"
end
end
When I call #body in the view, it is blank (#body.inspect) results in 'nil'. However, if I do something like: #{body} in place of the subject line, the text will render fine.
Anyone have any clue whats going on?
how about # user, is it displayed correctly? May be #body is used by rails, try rename.

Sending Emails to multiple comma separated email addresses

Hi I want to send emails to all the email comma addresses entered in text field. I have following controller for doing so.
def send_invites #friend invites
#emails_txt = params[:emails_txt]
#emails = #emails_txt.split(/\s*,\s*/)
#ve = []
#emails.each do |email|
if email =~ /\b[A-Z0-9._%a-z-]+#(?:[A-Z0-9a-z-]+.)+[A-Za-z]{2,4}\z/
#ve << email
end
end
#all_ok = true
#errors = []
#ve.each do |email|
#invitation = Invitation.new
#invitation.sender = current_user
#invitation.recipient_email = email
if #invitation.save
UserMailer.invitation_notification(current_user, #invitation, new_user_registration_url+"/#{#invitation.token}").deliver
else
#all_ok = "false"
#errors << #invitation.errors
end
end
end
It was working fine but now it is giving error as follows
NoMethodError in InvitationsController#send_invites
undefined method `username' for nil:NilClass
whats the problem please help me. Thank you
It looks like you are perhaps referencing a nil object in your email view.
I would look in your view for the UserMailer#invitation_controller action and see where you reference username.
Then, once you found that, trace back the object and find out why its nil, then add some testing around that (i.e. if current_user.nil? ...).

Resources