Friday, June 6, 2008

How to send a mail from application

After the configuration of action mailer. Perform the following task.

class Notifier < ActionMailer::Base
def send_email(user_details)
@recipients = "#{user[:email]}"
@from = "xyz@xyz.com"
@subject = "this is testing"
@sent_on = Time.now.utc
@content_type = "text/html"
@body = {}
url = "http://xyz.com/id=12312123"
@body.store('url', url)
@body.store('user', user)
render_message("signup", @body)
end
end


from controller call
def xyz
@user = User.new(params[:user])
if @user.save!
Notifier.send_email(@user)
end
end

and if you want a proper template should be forwarded then in ur view folder/notifier

create a file send_email.rhtml if you are using localization you can call as 'send_email_en.rhtml'
Dear, <%= @user[:login] %>
Welcome to xyz.com

thanks

About ActionMailer and condiguration of action mailer.

ActionMailer allows you to send email from your application, when you generate a action mailer
using following command: -
script/generate mailer Notifier
a action mailer class(inside model folder) and view generate.

Mailer methods have the following configuration methods available.
  • recipients - Takes one or more email addresses. These addresses are where your email will be delivered to. Sets the To: header.
  • subject - The subject of your email. Sets the Subject: header.
  • from - Who the email you are sending is from. Sets the From: header.
  • cc - Takes one or more email addresses. These addresses will receive a carbon copy of your email. Sets the Cc: header.
  • bcc - Takes one or more email address. These addresses will receive a blind carbon copy of your email. Sets the Bcc header.
  • sent_on - The date on which the message was sent. If not set, the header wil be set by the delivery agent.
  • content_type - Specify the content type of the message. Defaults to text/plain.
  • headers - Specify additional headers to be set for the message, e.g. headers ‘X-Mail-Count’ => 107370.
Configuration
1. First you need to configure action mailer with your application.
open environment.rb file or you can write it in a production/development file also.
after the 'Rails::Initializer.run do |config|' block
paste the below mention code

ActionMailer::Base.raise_delivery_errors = true #You may also turn exception raising on and off.
ActionMailer::Base.delivery_method=:smtp
ActionMailer::Base.smtp_settings = {
:address => "smtp.yourserver.com",
:port => 25,
#:domain => "www.mywebsite.com"
:user_name => "username",
:password => "password",
:authentication => :login # :plain, :login or :cram_md5
}
:domain is the name sent to the SMTP server during the handshake. It will be used to form the first “Received:” header, which spam filters usually check.