Mailer: Sending emails using Ruby on Rails failing
I have created a database of users in my Ruby on Rails app, and now I'm trying to create a mailer that send emails to all users in my database whenever I want.
Here's my model:
class MailMessage < ActionMailer::Base
def contact(recipient, subject, message)
# host = Hobo::Controller.request_host
# app_name = Hobo::Controller.app_name || host
@subject = subject
# @body = { :user => user, :host => host, :app_name => app_name }
@body["title"] = 'This is title'
@body["email"] = 'mark@doc.org.uk'
@body["message"] = message
@recipients = recipient
@from = 'no-reply@doc.org.uk'
@sent_on = Time.now
@headers = {}
end
end
Here's my controller:
class MailMessageController < ApplicationController
def sendmail
email = @params["email"]
recipient = email["recipient"]
subject = email["subject"]
message = email["message"]
MailMessage.deliver_contact(recipient, subject, message)
return if request.xhr?
render :text => 'Message sent successfully'
end
def index
render :file => 'app/views/mail_message/index.html'
end
end
Here's my views/mail_message
:
<h1>Send Email</h1>
<%= form_tag :action => 'sendmail' %>
<p>
<label for="email_subject">Subject</label>
<%= text_field 'email', 'subject' %>
</p>
<p>
<label for="email_recipient">Recipient</label>
<%= text_field 'email', 'recipient' %>
</p>
<p>
<label for="email_message">Message</label>
<%= text_area 'email', 'message' %>
</p>
<%= submit_tag "Send" %>
<%= form_tag %>
Here's my enviroment.rb
:
ActionMailer::Base.delivery_method = :sendmail
开发者_C百科ActionMailer::Base.sendmail_settings = {
:location => '/usr/sbin/sendmail',
:arguments => '-i -t'
}
ActionMailer::Base.perform_deliveries = true # the "deliver_*" methods are available
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.default_charset = "utf-8"
ActionMailer::Base.default_content_type = "text/html" # default: "text/plain"
ActionMailer::Base.default_mime_version = "1.0"
ActionMailer::Base.default_implicit_parts_order = [ "text/html", "text/plain"]
When I run a test message, I get the following error:
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]
app/controllers/mail_message_controller.rb:4:in `sendmail'
It doesn't seem to recognise sendmail
, but I have given its location. Any clues for how to fix this error will be very appreciated.
It looks like this line is the problem:
@params["email"]
If it's meant to be the data from the form, drop the @.
@params isint initialized in your controller.
You probably simple want to use params to get your http action parameters.
精彩评论