1
votes

I am trying to send mail using actionmailer on a Rails 3.0.1 application. Here is my setup

config/initializers/setup_mail.rb

ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
  :address              => "smtp.gmail.com",
  :port                 => 587,
  :domain               => "saidyes.co.uk",
  :user_name            => "username",
  :password             => "password",
  :authentication       => "plain",
  :enable_starttls_auto => true
}

ActionMailer::Base.default_url_options[:host] = "localhost:3000"
ActionMailer::Base.register_interceptor(DevelopmentMailInterceptor) if  Rails.env.development?

config/environments/development.rb

config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true

app/mailers/user_mailer.rb

class UserMailer < ActionMailer::Base
  default :from => "[email protected]"

  def self.registration_confirmation(user)
    @user = user
    attachments["rails.png"] = File.read("#{Rails.root}/public/images/rails.png")
    mail(:to => "#{user.email}", :subject => "Welcome")
  end
end

app/models/user.rb

require "#{Rails.root}/app/mailers/user_mailer" 

after_create :send_welcome_email

private 
def send_welcome_email
  UserMailer.registration_confirmation(self).deliver
end

The first error i got was an uninitialized constant UserMailer in my Users model class. I fixed it by adding the require at the top of the User model definition. Now I get

undefined local variable or method `attachments' for UserMailer:Class

I must have configured actionmailer incorrectly or my rails app is not configured correctly to use mailer.

Anyway any advice or help would be appreciated.

Cheers

1

1 Answers

2
votes

I think the simple problem you've encountered is that the mail methods should be defined on instances of your mailer class.

Namely it should be

class UserMailer < ActionMailer::Base
  def registration_confirmation(user)
    @user = user
    attachments["rails.png"] = File.read("#{Rails.root}/public/images/rails.png")
    mail(:to => "#{user.email}", :subject => "Welcome")
  end
end

Note there is no self

Take a look at the helpful Rails Guide on the subject

As in your example you'll still call the method on the class

UserMailer.registration_confirmation(user).deliver

The class method does some magic to instantiate an instance, and ensure the correct template is rendered.