Code Monkey home page Code Monkey logo

resque_mailer's Introduction

ResqueMailer

Gem Version Build Status

A gem plugin which allows messages prepared by ActionMailer to be delivered asynchronously. Assumes you're using Resque for your background jobs.

Note that recent (2.0+) versions of Resque::Mailer only work with Rails 3.x or later. For a version compatible with Rails 2, specify v1.x in your Gemfile.

Installation

Install the gem:

gem install resque_mailer

If you're using Bundler to manage your dependencies, you should add it to your Gemfile:

gem 'resque' # or a compatible alternative / fork
gem 'resque_mailer'

Usage

Include Resque::Mailer in your ActionMailer subclass(es) like this:

class MyMailer < ActionMailer::Base
  include Resque::Mailer
end

Now, when MyMailer.subject_email(params).deliver is called, an entry will be created in the job queue. Your Resque workers will be able to deliver this message for you. The queue we're using is imaginatively named mailer, so just make sure your workers know about it and are loading your environment:

QUEUE=mailer rake environment resque:work

Note that you can still have mail delivered synchronously by using the bang method variant:

MyMailer.subject_email(params).deliver!

Oh, by the way. Don't forget that your async mailer jobs will be processed by a separate worker. This means that you should resist the temptation to pass database-backed objects as parameters in your mailer and instead pass record identifiers. Then, in your delivery method, you can look up the record from the id and use it as needed. If you'd like, you can write your own serializer to automate such things; see the section on serializers below.

If you want to set a different default queue name for your mailer, you can change the default_queue_name property like so:

# config/initializers/resque_mailer.rb
Resque::Mailer.default_queue_name = 'application_specific_mailer'

This is useful when you are running more than one application using resque_mailer in a shared environment. You will need to use the new queue name when starting your workers.

QUEUE=application_specific_mailer rake environment resque:work

Custom handling of errors that arise when sending a message is possible by assigning a lambda to the error_handler attribute. There are two supported lambdas for backwards compatiability.

The first lamba will be deprecated in a future release:

Resque::Mailer.error_handler = lambda { |mailer, message, error|
  # some custom error handling code here in which you optionally re-raise the error
}

The new lamba contains two other arguments, action and args, which allows mailers to be requeued on failure:

Resque::Mailer.error_handler = lambda { |mailer, message, error, action, args|
  # Necessary to re-enqueue jobs that receieve the SIGTERM signal
  if error.is_a?(Resque::TermException)
    Resque.enqueue(mailer, action, *args)
  else
    raise error
  end
}

Resque::Mailer as a Project Default

If you have a variety of mailers in your application and want all of them to use Resque::Mailer by default, you can subclass ActionMailer::Base and have your other mailers inherit from an AsyncMailer:

# config/initializers/resque_mailer.rb
class AsyncMailer < ActionMailer::Base
  include Resque::Mailer
end

# app/mailers/example_mailer.rb
class ExampleMailer < AsyncMailer
  def say_hello(user_id)
    # ...
  end
end

Writing an Argument Serializer

By default, the arguments you pass to your mailer are passed as-is to Resque. This means you cannot pass things like database-backed objects. If you'd like to write your own serializer to enable such things, simply write a class that implements the class methods self.serialize(*args) and self.deserialize(data) and set Resque::Mailer.argument_serializer = YourSerializerClass in your resque_mailer initializer.

There's also Active Record serializer which allows you to pass AR models directly as arguments. To use it just do: Resque::Mailer.argument_serializer = Resque::Mailer::Serializers::ActiveRecordSerializer

Using with Resque Scheduler

If resque-scheduler is installed, two extra methods will be available: deliver_at and deliver_in. These will enqueue mail for delivery at a specified time in the future.

# Delivers on the 25th of December, 2014
MyMailer.reminder_email(params).deliver_at(Time.parse('2014-12-25'))

# Delivers in 7 days
MyMailer.reminder_email(params).deliver_in(7.days)

# Unschedule delivery
MyMailer.reminder_email(params).unschedule_delivery

Testing

You don't want to be sending actual emails in the test environment, so you can configure the environments that should be excluded like so:

# config/initializers/resque_mailer.rb
Resque::Mailer.excluded_environments = [:test, :cucumber]

Note: Define current_env if using Resque::Mailer in a non-Rails project:

Resque::Mailer.current_env = :production

Note on Patches / Pull Requests

  • Fork the project.
  • Make your feature addition or bug fix.
  • Add tests for it. This is important so I don't break it in a future version unintentionally.
  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
  • Send me a pull request. Bonus points for topic branches.

Credits

Developed by Nick Plante with help from a number of contributors.

resque_mailer's People

Contributors

adambird avatar adimichele avatar allenwei avatar andrewpbrett avatar dbackeus avatar elliterate avatar empact avatar fabiokr avatar glaucocustodio avatar glebm avatar greysteil avatar gsdean avatar hmarr avatar jamesgolick avatar jogaco avatar ku1ik avatar kurtfunai avatar maletor avatar petergoldstein avatar reneklacan avatar squidarth avatar wedgex avatar yoavmatchulsky avatar yujingz avatar zapnap avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

resque_mailer's Issues

test broken since 2.2.0

I use following code to test my mailer, but it no longer valid in resque_mailer 2.2.0, sounds in 2.2.0 PingMailer.manufacturer_info(@ping_mail.id) is no-op even in test env.

thanks

describe PingMailer do

  context "#manufacturer_info" do
    before :each do
      @user_reliable = create :user_reliable
      @ping_mail = create :ping_mail, :user => @user_reliable, :category => PingMailCategory::REQUEST_INFORMATION
      @ping_mail = PingMailDecorator.decorate(@ping_mail)
    end

    it "should works" do
      dm = PingMailer.manufacturer_info(@ping_mail.id)
      dm.to.should include(@ping_mail.to)
      dm.reply_to.should include(@user_reliable.email)
      dm.subject.should == @ping_mail.subject
      @ping_mail.reload
      @ping_mail.success.should be_true
      @ping_mail.error_info.should be_nil
    end
  end
end

Problems passing hash

Hi,

I'm having problems passing hash to the Mailer class.
In the messages controller i'm passing a hash of all parameters required by the mailer. In the mailer instance, I assign the hash to an instance variable.

Is it ok to send a hash of params as single argument to the mailer method?

My code is described in this gist: Gist

Thanks,
Roy

Attachments are not sent anymore since 2.0.0 upgrade

Hi,

Since we updated resque_mailer from 1.0.1 to 2.0.0, we experience an issue with attachments. In fact they aren't sent anymore at all :(
we are using rails 3.0.9 and resque 1.17.1

Everything is working fine again when we do one of these actions :

  • reverting to 1.0.1
  • removing "include resque_mailer" from mailer
  • using bang method deliver!

Here is the code used in the mailer for this email :

def documents_upload(user_id)
  user = User.find(user_id)

  user.documents.each do |doc|
    attachments["#{user_id}_#{doc.file_file_name}"] = { 
      :content_type => doc.file_content_type,
      :content => IO.read(doc.file.path) }
  end

  mail(:to => "[email protected]", :subject => user_id) do |format|
    format.text { render :text => ""} #no body needed for this email
  end
end

Document#file beeing a paperclip attachment.

I'll try to find more about that issue.

Olivier.

support for non rails app

I am using resque_mailer for s non rails project,but i get "uninitialized constant Rails" error. Does that mean i need rails?

thanks

Help testing against edge resque

Hey there!

I'm gearing up to work on Resque 2.0, and I'd like to coordinate better with plugin authors to make sure stuff doesn't break.

I'd like to know a few things:

  1. Can I do something to help get you testing against edge Resque?
  2. Are you monkey-patching anything in Resque currently? Can 2.0 expose an API to help you not have to do that any more?
  3. Do you need any help in bringing your plugin up-to-date with the latest Resque?

Thanks!

Related: https://github.com/defunkt/resque/issues/880

2.2.0 update tries to send mail in development even if excluded

Hello,
I recently updated resque_mailer from 2.0.3 to 2.2.0 and it seems to work fine in staging/production, however its giving me connection errors in development.

Errno::ECONNREFUSED in ContactsController#site_contact_form
Connection refused - connect(2)

in mailers/contact_mailer.rb I have:

include Resque::Mailer

in config/initializers/resque_mailer.rb I have:

Resque::Mailer.excluded_environments = [:test, :cucumber, :development]

But it will only work if I do:

include Resque::Mailer unless Rails.env.development?

or similar manual exclusion of including ResqueMailer.

If I comment out the include Resque::Mailer, it also will work. I downgraded back to 2.0.3 and it works as is. Expected behavior? I've read the site docs several times looking for a hint and haven't found anything. Let me know if I'm missing something.

undefined method `deliver'

Hi,

So when I do AutoMailer.resque.deliver:

class AutoMailer < ActionMailer::Base
  include Resque::Mailer

  default from: "[email protected]"

  # Subject can be set in your I18n file at config/locales/en.yml
  # with the following lookup:
  #
  #   en.auto_mailer.resque.subject
  #
  def resque
    @greeting = "Hi"

    mail to: "[email protected]"
  end
end

I get:

NoMethodError: undefined method `deliver' for Resque Client connected to redis://localhost:6379/0:Module
    from (irb):3
    from /Users/cj/.rvm/gems/ruby-1.9.3-p0@global/gems/railties-3.1.3/lib/rails/commands/console.rb:45:in `start'
    from /Users/cj/.rvm/gems/ruby-1.9.3-p0@global/gems/railties-3.1.3/lib/rails/commands/console.rb:8:in `start'
    from /Users/cj/.rvm/gems/ruby-1.9.3-p0@global/gems/railties-3.1.3/lib/rails/commands.rb:40:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

I'm using rails 3.1.3, any ideas on what might be going on?

Many thanks

Resque::Mailer as a Project Default example not working.

When trying out the code from the "Resque::Mailer as a Project Default" section in the readme, I get:

undefined method `perform' for LeagueMailer:Class

There's no such problem when including Resque::Mailer directly into my mailers.

deliver method not works

Hi! I've installed & configured Resque & Resque mailer and all my messages that were sent through .deliver method are going nowhere (there are no created queues), but i can see in console mailer log:

Sent mail to aaa@aaa.com (2ms)
Date: Wed, 25 Jul 2012 13:36:19 +0300
From: from@example.com
To: aaa@aaa.com
...

.deliver! works fine. Here is my mailer class:

class ClientMailer < ActionMailer::Base
  include Resque::Mailer
  layout 'client_mailer'

  default from: "[email protected]"
...
  def reminder(client_id)
    send_email(client_id, 'reminder')
  end
...
  private
    def send_email(id, type)
      client = Client.find(id, include: [:user])
      mail(to: client.email, subject: "Rafter Adoption #{type}")
    end
end

Call:

ClientMailer.reminder(@client.id).deliver

Instant delivery works good:

ClientMailer.reminder(@client.id).deliver!

I can't figure out why .deliver doesn't create mailer queue :(

DateTime objects are being converted to strings when passed to Mailer

I'm running into an issue where I'm passing a DateTime object as one of the parameters of a mailer, but when Resque::Mailer processes it, it treats it as a String.

Here is my code:

I have a rake task that calls AdminMailer.hourly_report:

desc 'Delivers hourly usage report'
  task deliver_hourly_report: :environment do
    Kernel.puts '     Delivering hourly report'

    time_end = Time.now.utc.beginning_of_hour
    time_start = time_end - 1.hour

    new_users_count = User.where('account_type = ? AND created_at BETWEEN ? AND ?', 0, time_start, time_end).count
    total_users_count = User.where('account_type = ? AND created_at <= ?', 0, time_end).count

    AdminMailer.hourly_report(new_users_count, total_users_count, time_start, time_end).deliver
  end
end

The hourly report then takes those parameters and uses them in the subject and body of the email:

class AdminMailer < ActionMailer::Base
  include Resque::Mailer

  default from: '[email protected]'

  def hourly_report(new_users_count, total_users_count, time_start, time_end)
    @start_friendly = time_start.strftime('%m-%d-%Y %H:%M')
    @end_friendly = time_end.strftime('%m-%d-%Y %H:%M')
    @new_users_count = new_users_count
    @total_users_count = total_users_count

    mail(to: '[email protected]', subject: "[Admin] Hourly Report #{@start_friendly} - #{@end_friendly}")
  end
end

If I run this without including Resque:Mailer, it works just fine. But with Resque:Mailer, I get the following error:

Unable to deliver email [hourly_report]: undefined method `strftime' for "2015-05-19T02:00:00.000Z":String

Why is Resque::Mailer converting the DateTime parameters into a String?

race condition / async problem when using resque_mailer with mail_view

I'm trying to use the mail_view gem together with resque_mailer.

It's used in development, when we don't actually send any email via resque.

As far as I understand it, the mail_view gem expects a mail object back, which it renders as a web page instead of logging or sending out. When we include Resque::Mailer in our mailer however, the mail object appears to be created asynchronously or something (even when we don't run any resque workers). This can lead to a race condition.

To demonstrate the problem please see gingerlime/resque_mailer_test@f703ee1

run the rails server, and then go to http://localhost:3000/mail_view/test

When the test mail is rendered, it displays the subject as xyz instead of abc...

p.s. deliver isn't being called here at all, only a mail object is created as far as I can tell

Support for rails3

I was going to fork your project to build support for this but ended up making my own little library. I'm not sure how it would fit into your project but here is the code:

https://gist.github.com/ddd9b63aff817c2a24b0

Let me know if this is helpful or if there are improvements I could make or help with on getting this integrated.

Cheers!

Resque Mailer sending emails with empty bodies

I'm having a problem with the mailer sending email with empty bodies.

config/initializers/resque_mailer.rb

Resque::Mailer.excluded_environments = [:test, :development]

class AsyncMailer < ActionMailer::Base
  include Resque::Mailer
end

app/mailers/example_mailer.rb

class ExampleMailer < AsyncMailer
  helper :application

  default from: "Me <[email protected]>"
  default "Message-ID" => lambda {"<#{SecureRandom.uuid}@example.com>"}

  def notify(example_id)
    @example = Example.find(example_id)
    mail(:subject=>"Example",:to=>"[email protected]")
  end

end

config/environments/production.rb

  config.action_mailer.default_url_options = { :host => 'www.example.com' }
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.perform_deliveries = true
  config.action_mailer.raise_delivery_errors = true

  config.action_mailer.smtp_settings = {
     :authentication => :plain,
     :address => "smtp.mailgun.org",
     :port => 587,
     :domain => "example.com",
     :user_name => "[email protected]",
     :password => "***********"
  }

ExampleMailer.notify(1).deliver! Renders the body, delivers normally
ExampleMailer.notify(1).deliver Renders a blank body, delivers but with a blank body

Has anyone encountered this before? I have commented out include Resque::Mailer from my config file in the meantime and emails are sending normally.

ArgumentError: wrong number of arguments (1 for 3)

When there are errors in views, resque_mailer simply throws the ArgumentError exception rather than raising the exception in the view.

This is the backtrace I get:

[GEM_ROOT]/gems/actionpack-3.1.2/lib/action_view/template/error.rb:60:in initialize' [GEM_ROOT]/bundler/gems/resque_mailer-c61531375878/lib/resque_mailer.rb:49:inexception'
[GEM_ROOT]/bundler/gems/resque_mailer-c61531375878/lib/resque_mailer.rb:49:in raise' [GEM_ROOT]/bundler/gems/resque_mailer-c61531375878/lib/resque_mailer.rb:49:inrescue in perform'
[GEM_ROOT]/bundler/gems/resque_mailer-c61531375878/lib/resque_mailer.rb:41:in `perform'

I'm gonna take a look at this later today.

I'm running Rails 3.1.2 with ERB templates. The way to replicate this bug is to intentionally cause an error in a mailer view (for instance by calling a method on a variable that doesn't exist), send an email, and then check your resque logs.

Resque Mailer seems to be sending duplicate mails

I'm running on Heroku.
My redis queue has only 1 job. When the worker wakes up and processes that queue here is what I'm seeing:

2013-03-28T05:35:40+00:00 app[mailer.1]: 5153d671b6aac7b3cd000001
2013-03-28T05:35:40+00:00 app[mailer.1]: merchant is: #Merchant:0x00000005659f28
2013-03-28T05:35:40+00:00 app[mailer.1]: Rendered merchant_mailer/welcome_email.html.erb (8.8ms)
2013-03-28T05:35:41+00:00 app[mailer.1]:
2013-03-28T05:35:41+00:00 app[mailer.1]: Sent mail to [email protected] (651ms)
2013-03-28T05:35:42+00:00 app[mailer.1]:
2013-03-28T05:35:42+00:00 app[mailer.1]: Sent mail to [email protected] (594ms)

Here is my Mailer class:

class MerchantMailer < ActionMailer::Base
include Resque::Mailer

default from: "[email protected]"

def welcome_email(merchant_id)
puts "#{merchant_id}"
@merc = Merchant.find(merchant_id)
puts "merchant is: #{@merc}"
mail(:to => "#{@merc.e}", :subject => "Welcome!").deliver
end
end

And sure enough I'm seeing 2 emails in the inbox.

data_fabric causing error to resque-mailer

I am using data_fabric from master branch for database replication and resque mailer for batch email processing. I found that data_fabric is causing below error to the resque-mailer. This error stops the processing of resque mailer and it usually occurs immediately after sending the first mail

PGError: ERROR: prepared statement "a3" already exists
: SELECT DISTINCT(attr.attname)
FROM pg_attribute attr
INNER JOIN pg_depend dep ON attr.attrelid = dep.refobjid AND attr.attnum = dep.refobjsubid
INNER JOIN pg_constraint cons ON attr.attrelid = cons.conrelid AND attr.attnum = cons.conkey[1]
WHERE cons.contype = 'p'
AND dep.refobjid = $1::regclass

Would you please help me out to resolve the above issue?

Note: The same type of issue I faced earlier and I resolved it using the code mentioned in below URL.
http://stackoverflow.com/questions/6137570/resque-enqueue-failing-on-second-run

Mail Interceptor not working

Hi,
Mail interceptor not working in my development environment. Resque mailer doesnt consider the configured interceptor. and it sends the mail to actual users in a dev environment. below the interceptor snippet

class DevelopmentMailInterceptor
  def self.delivering_email(message)
    message.subject = "[#{message.to}] #{message.subject}"
    message.to = "[email protected]"
  end
end
ActionMailer::Base.register_interceptor(DevelopmentMailInterceptor) if Rails.env.development?

Cheers

deliver! creates Mail::Message but doesn't send

class AsyncMailer < ActionMailer::Base
    include Resque::Mailer
 end

class OrderMailer < AsyncMailer
   def confirmation(order_id)
     order = Order.find order_id
     mail(:to => order.email, :subject => "test")
   end
end

OrderMailer.confirmation(Order.last.id).deliver
# Mail::Message:70284818200620...
# mail is queued and sent

OrderMailer.confirmation(Order.last.id).deliver!
# Mail::Message:70284818245666...
# mail is NOT sent

resque_mailer 2.0.2
actionmailer 3.1.3
ruby 1.9.2-p290

working with resque v2

Is resque_mailer compatibel with resque v2? I am having a hard time setting it up.

I get this message when I try to send a mail
NoMethodError: undefined method `[]' for nil:NilClass

UserMailer.welcome_email(user).deliver

Rails 3.1 issue

Does not work for me in Rails 3.1 application. (Everything is fine in my old 3.0.x app). Sounds like a local issue, or it's not only me?

Cannot use deliver_in

I'm trying to use the new deliver_in method, but not having any success.
I have resque_mailer (2.1.0) and resque-scheduler (2.0.0) in my gem file.

Here's what my code looks like:

#resque_mailer.rb
Resque::Mailer.excluded_environments = [:test, :cucumber]
#runs on queue +mailer+

# mailers inherit from this for async
class AsyncMailer < ActionMailer::Base
  include Resque::Mailer
  def welcome(user_id)
    @user = User.find(user_id)
    mail to: @user.email, subject: "Welcome"
  end
end

Then I try to call it with:

AsyncMailer.welcome(1).deliver_in(7.days)

And get the error message:

NoMethodError: undefined method `deliver_in' for #<Mail::Message:0x007f89339db750>

I can send the emails in the normal way with:

AsyncMailer.welcome(1).deliver

which works just fine. (Thank you for making that possible!) I'm not sure if I misunderstood the instructions in the README, or if there's something else going on.

Emails being sent

Rails 3.2.1 with Rspec 2.8.

We're transitioning to Resque from Delayed Job. I added resque_mailer and all is working well, but emails are being sent during testing, despite having this in an initiailzer:

Resque::Mailer.excluded_environments = [:test]

Is there something else I can check or configure to make sure they don't get sent?

Rake tasks not available on Rails 4.0.0

I've installed the resque_mailer (2.2.4) gem.

But something seems to have gone wrong, as it has not added any rake tasks.

$ rake -T resque # => nothing

If I start the worker with bundle exec resque work, then it fails on

resque-2.0.0.pre.1: Waiting for default
Timed out after 5.0 seconds
$ which resque
/Users/martins/.rvm/gems/ruby-2.0.0-p195@Kaffesmak/bin/resque

^ Yes, the its the correct binary at least.

Environmental variables in ActionMailer config

For some reason if I have environmental variables in my smtp_setting's it doesn't pass them to be authenticated in the background.

ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.smtp_settings = {
  address: "smtp.gmail.com",
  port: 587,
  domain: 'gmail.com',
  authentication: :login,
  enable_starttls_auto: true,
  user_name: ENV['EMAIL_USER'],
  password: ENV['EMAIL_PASS']
}

And in my mailer I have include Resque::Mailer at the top.
So when the mailer gets called I receive this error in my resque failed jobs.

Exception: Net::SMTPAuthenticationError
Error: 530-5.5.1 Authentication Required. Learn more at

I believe that means that it isn't passing the email and password in.

I'm not sure how to fix it either. Oh and it works if I remove the include for Resque::Mailer

Duplicate emails being sent

Hello...I've opened this issue before and withdrew it because I thought there may have been an issue with my code, but there really isn't.

Here is the log:

2013-06-25T02:47:46.272269+00:00 app[mailer.1]: merchant is: #lt;Merchant:0x00000004d44320>
2013-06-25T02:47:46.742166+00:00 app[mailer.1]: Rendered merchant_mailer/welcome_email.html.erb (6.2ms)
2013-06-25T02:47:47.604857+00:00 app[mailer.1]:
2013-06-25T02:47:47.604857+00:00 app[mailer.1]: Sent mail to [email protected] (772ms)
2013-06-25T02:47:48.187976+00:00 app[mailer.1]:
2013-06-25T02:47:48.187976+00:00 app[mailer.1]: Sent mail to [email protected] (583ms)

As you can see there are two "Sent mail to...." happening. This doesn't happen all the time. Sometimes it will only print that once in the log and hence I will receive only a single email.

I'm using SendGrid to send my emails. They don't know whats going on either.

Wondering if this is something specific to the RM and Sendgrid combo?

Thanks in advance for your assistance.

deliver_to and deliver_at doesn't work

When I use deliver_at and deliver_to I don't see any jobs in resque. Am I looking at it wrong?

require 'resque/tasks'
require 'resque/scheduler/tasks'
namespace :send_schedule_email do
  desc "Run and manage group of Resque workers with some default options"
  task :send => :environment do
    mails = Email.where('queued = ?', false)

    mails.each do |mail|
      #EmailQueue.enqueue_email(mail.id).deliver_at(Time.parse(mail.send_it_at.to_s))
      #EmailQueue.enqueue_email(mail.id).deliver_in(7.days)
#works
      EmailQueue.enqueue_email(mail.id).deliver
    end

  end


end

My gem file is like below

gem "resque" #https://github.com/resque/resque
gem 'resque-scheduler', :git => 'git://github.com/resque/resque-scheduler.git'
gem 'resque_mailer', :git => 'git://github.com/zapnap/resque_mailer.git' #https://github.com/zapnap/resque_mailer
gem 'resque-web', require: 'resque_web'

method_missing not fired, so resque_mailer enqueue not used

Hi,
thanks for providing this nice little but clean and usefull tool ;) Here is my problem :

If I manually put a mail deliver method in resque with enqueue method, it works well and my worker process the mailer queue successfully. But using the usual deliver method for my mailer, it never go to resque. After little debugging the error seems to come from the method_missing method which is not fired when calling a deliver_* method. It looks like the action_mailer method_missing function is processed instead of the resque_mailer one.
I don't understand why your method doesn't take predecence over the action_mailer one :/

I think I configure resque_mailer correctly since during debugging I can see resque_mailer in stack trace. Here is a gist with exemple : http://gist.github.com/335104

thanks for your help,

gonzoyumo.

worker crashes with Error: No such file or directory

when I have my Profile set to this:

worker: QUEUE=mailer bundle exec rake environment resque:work

I get this error:

2012-03-07T04:07:46+00:00 app[worker.1]: Error: No such file or directory - QUEUE=mailer bundle exec rake environment resque:work

I tried setting my Procfile to this:

worker: QUEUE=* bundle exec rake environment resque:work

And with this setting the worker doesn't crash but I also don't get any mail to go out.

Anyone used this gem on heroku and know if it works or what I'm missing?

uninitialized constant MyMailer!

I'm running Resque on rails 3.0.3/ruby 1.9.2.
I installed Resque Mailer and it just works fine as expected as adding mails to the queue.
but I goto an error in the Resque GUI about the job that its failed!

Class
NotificationMailer

Arguments
"welcome"
"[email protected]"

Exception
NameError

Error
uninitialized constant NotificationMailer

/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/resque-1.10.0/lib/resque/helpers.rb:58:in `const_get'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/resque-1.10.0/lib/resque/helpers.rb:58:in `block in constantize'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/resque-1.10.0/lib/resque/helpers.rb:57:in `each'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/resque-1.10.0/lib/resque/helpers.rb:57:in `constantize'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/resque-1.10.0/lib/resque/job.rb:174:in `payload_class'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/resque-1.10.0/lib/resque/job.rb:111:in `perform'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/resque-1.10.0/lib/resque/worker.rb:157:in `perform'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/resque-1.10.0/lib/resque/worker.rb:124:in `block in work'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/resque-1.10.0/lib/resque/worker.rb:110:in `loop'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/resque-1.10.0/lib/resque/worker.rb:110:in `work'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/resque-1.10.0/lib/resque/tasks.rb:24:in `block (2 levels) in <top (required)>'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/rake-0.8.7/lib/rake.rb:636:in `call'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/rake-0.8.7/lib/rake.rb:636:in `block in execute'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/rake-0.8.7/lib/rake.rb:631:in `each'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/rake-0.8.7/lib/rake.rb:631:in `execute'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/rake-0.8.7/lib/rake.rb:597:in `block in invoke_with_call_chain'
/Users/amr/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/monitor.rb:201:in `mon_synchronize'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/rake-0.8.7/lib/rake.rb:590:in `invoke_with_call_chain'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/rake-0.8.7/lib/rake.rb:583:in `invoke'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/rake-0.8.7/lib/rake.rb:2051:in `invoke_task'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/rake-0.8.7/lib/rake.rb:2029:in `block (2 levels) in top_level'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/rake-0.8.7/lib/rake.rb:2029:in `each'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/rake-0.8.7/lib/rake.rb:2029:in `block in top_level'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/rake-0.8.7/lib/rake.rb:2023:in `top_level'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/rake-0.8.7/lib/rake.rb:2001:in `block in run'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/rake-0.8.7/lib/rake.rb:1998:in `run'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/gems/rake-0.8.7/bin/rake:31:in `<top (required)>'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/bin/rake:19:in `load'
/Users/amr/.rvm/gems/ruby-1.9.2-p136@rails3/bin/rake:19:in `<main>'

and here is my Mailer

class NotificationMailer < ActionMailer::Base
  include Resque::Mailer

  def welcome(mail)
    mail(:to => mail, :subject => 'Welcome to Me!', :domain => 'xxzz.co') do |format|
      format.html
      format.text
    end
  end
end

Rails app won't start in production -- problem with config/initializers/resque_mailer.rb

I have an issue in my production environment that crashes my Rails app upon startup (the app never loads up fully). I'm not sure why this gem is the cause, but I do know that it is the source of the problem. Before this issue started, my app was working fine in production and this is what my config/initializers/resque_mailer.rb file looked like:

#config/intializers/resque_mailer.rb
Resque::Mailer.default_queue_name = "email"
Resque::Mailer.excluded_environments = [ :development, :test ]

# Setup a default mailer class that sends mail asynchronously
class AsyncMailer < ActionMailer::Base
  include Resque::Mailer
end

After my subsequent deploy broke the app, I tried to figure out what I had changed that could have caused the issue. After a lot of testing, gnashing of teeth, and many many git reverts, I was able to pinpoint the problem to one commit that changed the config/initializers/resque_mailer.rb file to the following:

#config/intializers/resque_mailer.rb
Resque::Mailer.default_queue_name = "email"
Resque::Mailer.excluded_environments = [ :development, :test ]

In essence, all I did was remove the AsyncMailer class, which I wasn't using anyway. However, when I try to deploy, the app won't start up and I get the following error:

You can no longer call ActionMailer::Base.default_url_options directly. You need to set config.action_mailer.default_url_options. If you are using ActionMailer standalone, you need to include the routing url_helpers directly.

This stems from ActionMailer::Base line 788 (in Rails 3.0.10), and I can't figure out why it's throwing this error. Nowhere in my code do I set ActionMailer::Base.default_url_options directly.

Now, the bright side is that I can revert my changes (and I already have, in production) and get the app working again. However, I never used the AsyncMailer class, instead I always added the include directly to whatever mailer needed it. So I would prefer not to have to add those lines back in, because it seems weird to me to have to include extra, unused classes in my app. Moreover, I'm absolutely confounded as to how these lines could be causing the problem, but I'm also absolutely sure that they are in fact the cause of this issue. Any help or insight would be greatly appreciated!

Note that I CANNOT reproduce this error in development, no matter what I do.
My production environment runs Ruby 1.9.3, Rails 3.0.10, Passenger 3.0.11 and nginx 1.0.10 and the latest version of the resque_mailer gem.

Different queues for different mailers?

Not an issue so much as a question: is it possible to use different queues for different mailers? If so, how? Some emails are higher-priority than others in our app.

Thanks for the great plugin!

The action 'xxxx' could not be found for XptoMailer

AbstractController::ActionNotFound
The action 'enviar_confirmacao' could not be found for RecargaMailer

#mailer
class RecargaMailer < ActionMailer::Base
  include Resque::Mailer

  default from: "[email protected]"

  def enviar_confirmacao(user)
    mail(:to => user.email, :subject => "Confirmação de recarga")
  end
end

#controller
RecargaMailer.enviar_confirmacao(current_user).deliver

rails (3.2.3)
resque_mailer (2.0.3)

Just for information, if I remove "include Resque::Mailer" it works like a charm.

Making environment available to resque workers

Trying to call Model.find in my mailer deliver method, but getting this error in Resque:

uninitialized constant ModelMailer::Model

I can send mail synchronously, so I'm deducing that my worker isn't loading the environment correctly. I've tried:

$ QUEUE=* rake environment resque:work

and I've tried the rake setup task:

lib/tasks/resque.rake

require "resque/tasks"

task "resque:setup" => :environment

Still the same error. Really want to avoid passing a full object to the deliver method, but will until I can figure this out. Thank you for your help.

Kimball

undefined method `perform'

I can't get this to work.

That's my CronMailer class

class CronMailer < ActionMailer::Base
include Resque::Mailer
def notification_email(alert_id)
    alert = UserAlert.find(alert_id)
    recipients alert.user.email
    from "myaddress@xx"
    subject "Alert"
    body alert.notification.message
end
end

I call it with:
CronMailer.notification_email(alert.id).deliver

and I always see this in admin console:
Class CronMailer
Arguments "notification_email"
108
Exception NoMethodError
Error undefined method 'perform' for CronMailer:Class
/var/lib/gems/1.9.1/gems/actionmailer-3.1.0/lib/action_mailer/base.rb:455:in 'method_missing'

So thw worker starts but it seems like it doesn't understand it's a resqueEmailer

Rescuing from exceptions

Hi! Thanks for the awesome gem btw.

Was wondering if there was a good way rescue from exceptions in resque mailer. For example, we are using AWS and sometimes get back AWS::SimpleEmailService::Errors::MessageRejected exceptions for black listed emails. Would be nice to capture these.

I was thinking about overriding the Resque::Mailer module in an initializer and wrapping perform. Or maybe there is a way to just rescue from ActionMailer deliver generally?

Thanks for any pointers.

Support for locale (and timezone)

I've used your gem in an existing project which send localized emails and on first deploy I got some issues due to missing locale support. Here's my use case, I have a mailer which uses layouts and those layouts shows localized links something like

<%= link_to t('some_key'), some_url %>

I was sending messages directly in the controller and links and other translated stuff is localized correctly since in controller I18n.locale is set according to user locale. When I moved to resque_mailer obviously that code has stopped to work.

In my project I was able to retrieve user locale from the mailer and I've solved with this code in my mailer, but this is not always possible.

def mailer(user_id)
  @user = User.find(user_id)
  I18n.with_locale(@user.locale) { mail(...) }
end

The same issue can appear if mail content is timezone dependent (wasn't my case) so this should be handled by gem.

This could be solved with something like

# in deliver
env = {locale: I18n.locale, timezone: Time.zone.name}
resque.enqueue(@mailer_class, @method_name, env, *@args)
# in perform
I18n.with_locale(env['locale']) do
  Time.use_zone(env['timezone']) do
    message = self.send(:new, action, *args).message
    message.deliver              
  end
end

This however would change main methods signatures, so it would need some specs.

What do you think? Are you interested in this kind of PR? Otherwise you should mention this issue in readme.

How to make the resque_mailer job appear in Resque-Job-With-Status?

I'm using resque-job-with-status and all the jobs gets listed in that tab.

But using resque_mailer, I'm confused how to make the mailer queue job also appear in the resque-job-with-status?

As per resque-job-with-status, to make it appear in the tab, the class has to extend from Resque::JobWithStatus, but for resque_mailer, it has to extend from ActionMailer::Base and has to include Resque::Mailer in the Mailer class?

So, since I cannot extend my Mailer class from both ActionMailer::Base and Resque-job-with-status, how to make it work as I'm expecting?

catch the correct redis error in MessageDecoy#deliver

When my redis server is down, I get this error when trying to use deliver:
Redis::CannotConnectError: Error connecting to Redis on localhost:6379 (ECONNREFUSED)

instead of Errno::ECONNREFUSED, which is catched and then calls deliver!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.