Sending Emails to multiple comma separated email addresses - ruby-on-rails

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? ...).

Related

undefined method `id' for "#<User:0x00007fe6d52c9c50>":String in ruby on rails

i did a button in html that when you press it send to the controller the current_user, so after that i want to work with that user in the controller but when i try to access to the atribute of the object user appears a problem saying that my object user is a string and a really don t know how trasform it to a object again, this is my code and the error:
Error:
NoMethodError in ArticlesController#show
undefined method `id' for "#<User:0x00007fe6d52c9c50>":String
Extracted source (around line #66):
puts params[:petition] user = params[:petition] puts user.id # user = User.find(params[:petition]) # puts datos.email # $list_of_petition.push(user)
code of the html:
<!--hacer boton de peticion-->
<form action=<%article_path(#article)%>>
<label for="petition">mail del usuario que se <br> convertira en moderador:</label>
<button name="petition" value=<%=current_user%> type="submit">pedir moderar</button>
</form>
code of my Articlescontroller:
def show
#article = Article.find(params[:id])
#posts = #article.posts
puts "fijate men"
puts params[:q]
puts params[:petition]
if params[:q] != nil
#answer = Search()
puts "aqui deveria ir respuesta"
puts #answer
end
if params[:petition] != nil
puts "miar aqui plspslpsl"
puts params[:petition].inspect
#respond = ask_to_admin()
end
end
def ask_to_admin
puts "hola"
puts params[:petition]
user = params[:petition]
puts user.id
i know that there is a way replacing the current_user for current_user.idand after in the controller make user = User.find(params[:petition]) but i dont what that, what to send the whole user.
In your code user=params[:petition] means assigning user variable a string.
You can't pass current_user through params. Instead, you should pass the current_user.id and in your controller, you can do something like below:
user = User.find params[:id]
Always remember params is an instance of ActionController::Parameters and behaves like a hash object and when you try to pass current_user or any other record within params, Actually you're just passing a String. So always pass the record id in params

Issues Looping through an array in Active Mailer

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.

Rails mailer error: wrong number of arguments (1 for 2)

Controller
def mail_test
#user = User.all.first
#course = Course.all.first
examplemailer.student_reminder(#user, #course).deliver
redirect_to '/'
end
Mailer controller
def student_reminder(user, course)
#user = user
#course = course
#url = 'http://www.google.com'
mail to: #user.email, subject: "Good Job!"
end
Here, I need to use <%=#user.name%> and <%= #course.title%>.
However, that code doesn't work, ending in the error
ArgumentError in Rails::MailersController#preview
wrong number of arguments (1 for 2)
at
def student_reminder(user, course)
I think I have proper number of arguments (user and course)
As noted above, the error was in the MailerController#preview method.

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.

ActiveSupport::TimeWithZone failed error in ruby on rails

I'm using code identical to my password_reset code for my email change code.
User wants change their email address so they type in their email address click a button and they're logged out.
An email is sent to them containing a link they click containing a code as id which is then matched up with the one stored in the db to confirm they are in fact the accounts owner. Any way when I click the I get the error shown below.
Problem is I'm getting this error:
ArgumentError in EmailsController#edit
comparison of String with ActiveSupport::TimeWithZone failed
Rails.root: /Users/greg/site
Application Trace | Framework Trace | Full Trace
app/controllers/emails_controller.rb:19:in `<'
app/controllers/emails_controller.rb:19:in `edit'
Request
Parameters:
{"id"=>"KdFTTeWuOGqpDm6F_iY7aw"}
Show session dump
Show env dump
Response
Headers:
None
Emails controller create:
def create
#user = User.find_by_email(params[:email_change][:email])
logout if logged_in?
#user.generate_and_store_email_change_token && UserMailer.email_change(#user).deliver if #user
flash[:success] = "Email sent with email reset instructions."
redirect_to root_url
end
Emails controller edit:
def edit
#user = User.find_by_email_change_token(params[:id])
if #user.nil?
flash[:error] = "The email change link you clicked has been used."
redirect_to root_url
elsif #user.email_change_sent_at < 2.hours.ago
flash[:error] = "Email change token has expired."
redirect_to email_change_url
end
end
User model:
def generate_and_store_email_change_token
self.email_change_token = SecureRandom.urlsafe_base64
self.email_change_sent_at = Time.zone.now
save!(:validate => false)
end
def remove_used_email_change_token
self.email_change_token = nil
save!(:validate => false)
end
This is strange because the exact same code works for my password reset. I tested again and I don't get the error the email version giving me.
Kind regards
Seems like email_change_sent_at type is a string. You should change it to datetime

Resources