Ruby on Rails - One user sending an email to another user - mailer

247 views Asked by At

I want one user to be able to send an email to another user by clicking a button. They will receive an auto generated email saying 'You have been challenged by [user]!' So on a view there will be a drop down menu to select from the list of users, and then a 'challenge' button which will send this email to that user. I already have mailer set up that sends a registration email.

Here's the email:

<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
</head>
 <body>
<h1>You have been challeneged by, <%= @opponent.student_name %>.</h1>

 </body>
</html> 

Here's my usermailer.rb (my users are called 'student')

  def welcome(student)
    @student = student

    mail(:to => student.email, :subject => "Welcome to the DIT Judo club!")
  end

  def challenge(student, opponent)
    @student = student
    @opponent = opponent
    mail(:to => student.email, :subject => "You have been challeneged to a Judo match!")
  end
end

Here's the config mailer stuff in case you want to see it:

  config.action_mailer.raise_delivery_errors = true

  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings ={
        :enable_starttls_auto => true,
        :address => 'smtp.gmail.com',
        :port => 587,
        :domain => 'smtp.gmail.com',
        :authentication => :plain,
        :user_name => 'xxxxx',
        :password => 'xxxxxx'
  }

So basically in a view I want to have a drop down where the current user(student) selects another user(student) and then you can click submit to trigger the challenge email. I'm new to rails can someone help me do it?

Here's my feeble attempt:

In the routes folder:

  get 'challenge', :to=>'usermailer#challenge'

  resources :matches do
        put :challenge
  end

In my index:

<div>
Challenge another student to a match!
  <div class="field">
    <%= f.label :opponent %><br> 

    <%= f.collection_select :opponent, Student.all, :id, :student_name %> 
  </div>
    <%= link_to 'challenge', match challenge_path([current studentID ??], [opponent from  collection]), method: :put %>

</div>
1

There are 1 answers

5
Brian On

Your welcome and challenge methods are just creating and returning a mail object. You need to call deliver on the mail object to actually send it. See "Calling the Mailer" in the documentation for more details.