Code Monkey home page Code Monkey logo

mandrill_mailer's Introduction

Mandrill Mailer

Build Status Gem Version Inline Documentation

Inherit the MandrillMailer class in your existing Rails mailers to send transactional emails through Mandrill using their template-based emails.

Installation

Add this line to your application's Gemfile:

gem 'mandrill_mailer'

And then execute:

$ bundle install

Or install it yourself as:

$ gem install mandrill_mailer

Usage

Add the following to your mail.rb in your Rails app's config/initializers directory:

ActionMailer::Base.smtp_settings = {
    :address   => "smtp.mandrillapp.com",
    :port      => 587,
    :user_name => ENV['MANDRILL_USERNAME'],
    :password  => ENV['MANDRILL_API_KEY'],
    :domain    => 'heroku.com'
  }
ActionMailer::Base.delivery_method = :smtp

MandrillMailer.configure do |config|
  config.api_key = ENV['MANDRILL_API_KEY']
  config.deliver_later_queue_name = :default
end

You don't need to add the ActionMailer stuff unless you're still using ActionMailer emails.

This uses the Mandrill SMTP servers. If you're using template-based emails through the Mandrill API you only need the MandrillMailer.configure portion.

Do not forget to setup the environment (ENV) variables on your server instead of hardcoding your Mandrill username and password in the mail.rb initializer.

You will also need to set default_url_options for the mailer, similar to ActionMailer in your environment config files in config/environments:

config.mandrill_mailer.default_url_options = { :host => 'localhost' }

Creating a new mailer

Creating a new Mandrill mailer is similar to a typical Rails one:

class InvitationMailer < MandrillMailer::TemplateMailer
  default from: '[email protected]'

  def invite(invitation)
    # in this example `invitation.invitees` is an Array
    invitees = invitation.invitees.map { |invitee| { email: invitee.email, name: invitee.name } }

    mandrill_mail(
      template: 'group-invite',
      subject: I18n.t('invitation_mailer.invite.subject'),
      to: invitees,
        # to: invitation.email,
        # to: { email: invitation.email, name: 'Honored Guest' },
      vars: {
        'OWNER_NAME' => invitation.owner_name,
        'PROJECT_NAME' => invitation.project_name
      },
      important: true,
      inline_css: true,
      recipient_vars: invitation.invitees.map do |invitee|
        { invitee.email =>
          {
            'INVITEE_NAME' => invitee.name,
            'INVITATION_URL' => new_invitation_url(
              invitee.email,
              secret: invitee.secret_code
            )
          }
        }
      end
     )
  end
end
  • #default:

    • :from - set the default from email address for the mailer. Defaults to '[email protected]'.
    • :from_name - set the default from name for the mailer. If not set, defaults to from email address. Setting :from_name in the .mandrill_mail overrides the default.
    • :merge_vars - set some default merge_vars that will be sent with every mailer method (in global_merge_vars so there's no risk of collision with method-specific merge_vars.
    • :view_content_link - set a default to be able to access individual mailer messages in the Mandrill dashboard. Defaults to false.
  • .mandrill_mail

    • :template(required) - Template slug from within Mandrill (for backwards-compatibility, the template name may also be used but the immutable slug is preferred)

    • :subject - Subject of the email. If no subject supplied, it will fall back to the template default subject from within Mandrill

    • :to(required) - Accepts an email String, a Hash with :name and :email keys, or an Array of Hashes with :name, :email, and :type keys

    • :vars - A Hash of merge tags made available to the email. Use them in the email by wrapping them in *||*. For example {'OWNER_NAME' => 'Suzy'} is used by doing: *|OWNER_NAME|* in the email template within Mandrill

    • :recipient_vars - Similar to :vars, this is a Hash of merge vars specific to a particular recipient. Use this if you are sending batch transactions and hence need to send multiple emails at one go. ex. [{'[email protected]' => {'INVITEE_NAME' => 'Roger'}}, {'[email protected]' => {'INVITEE_NAME' => 'Tommy'}}]

    • :template_content - A Hash of values and content for Mandrill editable content blocks. In MailChimp templates there are editable regions with 'mc:edit' attributes that look like: <div mc:edit="header">My email content</div> You can insert content directly into these fields by passing a Hash {'header' => 'my email content'}

    • :headers - Extra headers to add to the message (currently only Reply-To and X-* headers are allowed) {"...": "..."}

    • :bcc - Add an email to bcc to

    • :tags - Array of Strings to tag the message with. Stats are accumulated using tags, though we only store the first 100 we see, so this should not be unique or change frequently. Tags should be 50 characters or less. Any tags starting with an underscore are reserved for internal use and will cause errors.

    • :google_analytics_domains - Array of Strings indicating for which any matching URLs will automatically have Google Analytics parameters appended to their query string automatically.

    • :google_analytics_campaign - String indicating the value to set for the utm_campaign tracking parameter. If this isn't provided the email's from address will be used instead.

    • :important - whether or not this message is important, and should be delivered ahead of non-important messages.

    • :inline_css - whether or not to automatically inline all CSS styles provided in the message HTML - only for HTML documents less than 256KB in size.

    • :merge_language - the merge tag language to use when evaluating merge tags, either 'mailchimp' or 'handlebars'. Default is 'mailchimp'.

    • :attachments - An array of file objects with the following keys:

      • content: The file contents, this will be encoded into a base64 string internally
      • encoded_content (optional): File content already encoded into base64 string. Overrides content
      • name: The name of the file
      • type: This is the mimetype of the file. Ex. png = image/png, pdf = application/pdf, txt = text/plain etc etc
    • :images - An array of embedded images to add to the message:

      • content: The file contents, this will be encoded into a base64 string internally
      • encoded_content (optional): File content already encoded into base64 string. Overrides content
      • name: The name of the file
      • type: This is the mimetype of the file. Ex. png = image/png, pdf = application/pdf, txt = text/plain etc etc etc
    • :async - Whether or not this message should be sent asynchronously

    • :ip_pool - The name of the dedicated ip pool that should be used to send the message

    • :send_at - When this message should be sent

Sending a message without template

Sending a message without template is similar to sending a one with a template. The biggest change is that you have to inherit from MandrillMailer::MessageMailer instead of the MandrillMailer::TemplateMailer class:

class InvitationMailer < MandrillMailer::MessageMailer
  default from: '[email protected]'

  def invite(invitation)
    # in this example `invitation.invitees` is an Array
    invitees = invitation.invitees.map { |invitee| { email: invitee.email, name: invitee.name } }

    # no need to set up template and template_content attributes, set up the html and text directly
    mandrill_mail subject: I18n.t('invitation_mailer.invite.subject'),
                  to: invitees,
                  # to: invitation.email,
                  # to: { email: invitation.email, name: 'Honored Guest' },
                  text: "Example text content",
                  html: "<p>Example HTML content</p>",
                  # when you need to see the content of individual emails sent to users
                  view_content_link: true,
                  vars: {
                    'OWNER_NAME' => invitation.owner_name,
                    'PROJECT_NAME' => invitation.project_name
                  },
                  important: true,
                  inline_css: true,
                  attachments: [
                    {
                      content: File.read(File.expand_path('assets/offer.pdf')),
                      name: 'offer.pdf',
                      type: 'application/pdf'
                    }
                  ],
                  recipient_vars: invitation.invitees.map do |invitee| # invitation.invitees is an Array
                    { invitee.email =>
                      {
                        'INVITEE_NAME' => invitee.name,
                        'INVITATION_URL' => new_invitation_url(invitee.email, secret: invitee.secret_code)
                      }
                    }
                  end
  end
end

Sending an email

You can send the email by using the familiar syntax:

InvitationMailer.invite(invitation).deliver_now InvitationMailer.invite(invitation).deliver_later(wait: 1.hour) For deliver_later, Active Job will need to be configured

Creating a test method

When switching over to Mandrill for transactional emails we found that it was hard to setup a mailer in the console to send test emails easily (those darn designers), but really, you don't want to have to setup test objects everytime you want to send a test email. You can set up a testing 'mock' once and then call the .test method to send the test email.

You can test the above email by typing: InvitationMailer.test(:invite, email:<your email>) into the Rails Console.

The test for this particular Mailer is setup like so:

test_setup_for :invite do |mailer, options|
    invitation = MandrillMailer::Mock.new({
      email: options[:email],
      owner_name: 'foobar',
      secret: rand(9000000..1000000).to_s
    })
    mailer.invite(invitation).deliver
end

Use MandrillMailer::Mock to mock out objects.

If in order to represent a url within a mock, make sure there is a url or path attribute, for example, if I had a course mock and I was using the course_url route helper within the mailer I would create the mock like so:

course = MandrillMailer::Mock.new({
  title: 'zombies',
  type: 'Ruby',
  url: 'http://funzone.com/zombies'
})

This would ensure that course_url(course) works as expected.

The mailer and options passed to the .test method are yielded to the block.

The :email option is the only required option, make sure to add at least this to your test object.

Offline Testing

You can turn on offline testing by requiring this file (say, in your spec_helper.rb):

require 'mandrill_mailer/offline'

And then if you wish you can look at the contents of MandrillMailer.deliveries to see whether an email was queued up by your test:

email = MandrillMailer.deliveries.detect { |mail|
  mail.template_name == 'my-template' &&
  mail.message['to'].any? { |to| to[:email] == '[email protected]' }
}
expect(email).to_not be_nil

Don't forget to clear out deliveries:

before :each { MandrillMailer.deliveries.clear }

Using Delayed Job

The typical Delayed Job mailer syntax won't work with this as of now. Either create a custom job or queue the mailer as you would queue a method. Take a look at the following examples:

def send_hallpass_expired_mailer
  HallpassMailer.hallpass_expired(user).deliver
end
handle_asynchronously :send_hallpass_expired_mailer

or using a custom job

def update_email_on_newsletter_subscription(user)
  Delayed::Job.enqueue( UpdateEmailJob.new(user_id: user.id) )
end

The job looks like (Don't send full objects into jobs, send ids and requery inside the job. This prevents Delayed Job from having to serialize and deserialize whole ActiveRecord Objects and this way, your data is current when the job runs):

class UpdateEmailJob < Struct.new(:user_id)
  def perform
    user = User.find(user_id)
    HallpassMailer.hallpass_expired(user).deliver
  end
end

Using Sidekiq

Create a custom worker:

class UpdateEmailJob
  include Sidekiq::Worker
  def perform(user_id)
    user = User.find(user_id)
    HallpassMailer.hallpass_expired(user).deliver
  end
end

#called by
UpdateEmailJob.perform_async(<user_id>)

Or depending on how up to date things are, try adding the following to config/initializers/mandrill_mailer_sidekiq.rb

::MandrillMailer::TemplateMailer.extend(Sidekiq::Extensions::ActionMailer)

This should enable you to use this mailer the same way you use ActionMailer. More info: https://github.com/mperham/sidekiq/wiki/Delayed-Extensions#actionmailer

Using Resque

Create a job:

class SendUserMailJob
  def initialize(user_id)
    @user_id = user_id
  end

  def work
    user = User.find(@user_id)
    UserMailer.send_user_email(user).deliver
  end
end

Send your job to Resque:

resque = Resque.new
resque << SendUserMailJob.new(<user id>)

Using an interceptor

You can set a mailer interceptor to override any params used when you deliver an e-mail. The interceptor is a Proc object that gets called with the mail object being sent to the api.

Example that adds multiple bcc recipients:

MandrillMailer.configure do |config|
  config.interceptor = Proc.new {|params|

    params["to"] =  [
      params["to"],
      { "email" => "[email protected]", "name" => "name", "type" => "bcc" },
      { "email" => "[email protected]", "name" => "name", "type" => "bcc" },
      { "email" => "[email protected]", "name" => "name", "type" => "bcc" }
    ].flatten
  }
end

mandrill_mailer's People

Contributors

alejeune avatar arthurtalkgoal avatar benruns avatar berkos avatar eric1234 avatar ernsheong avatar icortex avatar jessieay avatar kennethkalmer avatar kfaustino avatar koppen avatar laserlemon avatar lrdiv avatar maxim-filimonov avatar mschulkind avatar nathanbertram avatar olivierlacan avatar pat avatar pichot avatar raphaelpra avatar renz45 avatar sideshowbandana avatar snatchev avatar srbiv avatar stevenjl avatar tompesman avatar traviskroberts avatar turlockmike avatar viniciusoyama avatar werme 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

mandrill_mailer's Issues

documentation not correct for interceptor_params

The configuration at the bottom of the readme didn't work with mandrill_mail and a template.

Here's my model:

class UserMailer < MandrillMailer::TemplateMailer
    def welcome (user)
      mandrill_mail template: 'awaiting-approval',
        to: {email: user.email, name: user.name},
        vars: {
          'FIRST_NAME' => user.first_name
        },
        important: true,
        inline_css: true,
        async: true
    end

end

I ended up doing it like so:

MandrillMailer.configure do |config|
    config.interceptor_params = { to: [email: '[email protected]', name: 'Homer Simpson'] }
end

Preserve Recipients default

      args[:preserve_recipients] = args[:preserve_recipients].nil? ? true : format_boolean(args[:preserve_recipients])

This should be false by default or removed completely so Mandrill's sending option will take precedence. Exposing people's email addresses by default is a terrible idea.

Integrated with delayedjob

Hi,

How would I send the email in the background using delayed-jobs?
With ActionMailer you have to go:
MyMailer.delay.some_email instead of
MyMailer.delay.some_email.deliver

But neither method works with mandrill_mailer

URL Helpers not working with Template Mailer on Heroku

I was wondering if this line was commented out for a reason? (on Line 81, lib/mandrill_mailer/template_mailer.rb)

# include Rails.application.routes.url_helpers

I seem to be having issues with the URL helpers in production in a way that I can't quite mimic on my development machine. Particularly, I can't seem to have the Template Mailer user URL helpers.

Issue using sidekiq delayed extensions

I am able to send mails using mandrill mailer, when I try to use sidekiq with delayed extensions it does not work.

(UserMailer is Mandrill template mailer here)
UserMailer.reset_password_instructions(@user, reset_url).deliver works!

Then based on the readme I added the app/config/initializers/mandrill_mailer_sidekiq.rb with

::MandrillMailer::TemplateMailer.extend(Sidekiq::Extensions::ActionMailer)

Then tried to deliver the mail asynchronously using UserMailer.delay.reset_password_instructions(@user, reset_url) But this throws an error in the sidekiq like this

2014-03-26T04:59:02Z 3520 TID-4ru7wk Sidekiq::Extensions::DelayedMailer JID-669579e667986028f88ed011 INFO: start
2014-03-26T04:59:02Z 3520 TID-4ru7wk Sidekiq::Extensions::DelayedMailer JID-669579e667986028f88ed011 INFO: fail: 0.003 sec
2014-03-26T04:59:02Z 3520 TID-4ru7wk WARN: {"retry"=>true, "queue"=>"default", "class"=>"Sidekiq::Extensions::DelayedMailer", "args"=>["---\n- !ruby/class 'UserMailer'\
n- :reset_password_instructions\n- - !ruby/object:User\n    attributes:\n      id: 1\n      name: cool\n      admin: true\n      email: [email protected]\n      encrypted
_password: \"$2a$10$G6bXQiLnFA6E3q41lPqlb.LcZxfn/MREIEdlzWgrbIcLR/ilI.CgS\"\n      reset_password_token: c1c56b1d3ebe4566a3c118b671bf39b6e6bc1e9a8e485c976fb01d267401078
1\n      reset_password_sent_at: 2014-03-25 18:25:17.996987000 Z\n      remember_created_at: \n      sign_in_count: 6\n      current_sign_in_at: 2014-03-25 17:53:33.106
915000 Z\n      last_sign_in_at: 2014-03-24 16:40:18.284724000 Z\n      current_sign_in_ip: 127.0.0.1\n      last_sign_in_ip: 127.0.0.1\n      confirmation_token: \n   
   confirmed_at: 2014-03-22 11:16:08.944241000 Z\n      confirmation_sent_at: 2014-03-22 11:16:08.671900000 Z\n      unconfirmed_email: \n      created_at: 2014-03-22 1
1:16:07.895242000 Z\n      updated_at: 2014-03-25 18:25:17.997698000 Z\n      role: \n      receive_order: true\n      receive_tribute: true\n      uploaded_video: true
\n  - http://www.example.com/users/password/edit?reset_password_token=c1c56b1d3ebe4566a3c118b671bf39b6e6bc1e9a8e485c976fb01d2674010781\n"], "jid"=>"669579e667986028f88e
d011", "enqueued_at"=>1395809942.582676, "error_message"=>"undefined method `to' for #<UserMailer:0x23a3dc98>", "error_class"=>"NoMethodError", "failed_at"=>1395809942.
5866923, "retry_count"=>0}
2014-03-26T04:59:02Z 3520 TID-4ru7wk WARN: undefined method `to' for #<UserMailer:0x23a3dc98>
2014-03-26T04:59:02Z 3520 TID-4ru7wk WARN: /home/vysakh/.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/bundler/gems/mandrill_mailer-22d69aa347b9/lib/mandrill_mailer/template
_mailer.rb:323:in `method_missing'
/home/vysakh/.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/sidekiq-2.17.7/lib/sidekiq/extensions/action_mailer.rb:20:in `perform'
/home/vysakh/.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/sidekiq-2.17.7/lib/sidekiq/processor.rb:49:in `block (3 levels) in process'
/home/vysakh/.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/sidekiq-2.17.7/lib/sidekiq/middleware/chain.rb:122:in `call'

I checked with action mailer, this delay function of sidekiq works! Did i miss something or is this a bug?

Should not warn about missing from option when default address set

I assume this is an bug rather than intended behaviour. If a default address is set e.g.

default from: "[email protected]"

but no from option is specified in the call to mandrill_mail the following warning is produced

Mandrill Mailer Warn: missing required option: from

The from option should be set by the default from option so there is no warning.

I'm happy to submit a PR if this should be fixed.

Thanks

Active Job Support

Are there currently any plans for this to work with Active Job? I know the "deliver" method will be deprecated and the deliver_now and deliver_later methods don't currently work with the template mailer. Thanks!

Defaults set on a child class wipe out all defaults form the parent class

Example:

class MailerBase < MandrillMailer::TemplateMailer
  default from: "[email protected]",
          from_name: "Example",
          view_content_link: true
end

class FunMailer < MailerBase
  default view_content_link: false
end

The FunMailer will now have from_name and from reset to the mandrill_mailer defaults, not the MailerBase. So basically we need to fix this:

def self.default(args)
@defaults ||= {}
@defaults[:from] ||= '[email protected]'
@defaults[:merge_vars] ||= {}
@defaults.merge!(args)
end

From this:

def self.default(args)
      @defaults ||= {}
      @defaults[:from] ||= '[email protected]'
      @defaults[:merge_vars] ||= {}
      @defaults.merge!(args)
    end

To this:

def self.default(args)
      @defaults ||= {}
      @defaults[:from] ||= (super_defaults[:from] || '[email protected]')
      @defaults[:merge_vars] ||= (super_defaults[:merge_vars]|| {})
      @defaults.merge!(args)
    end

Makes sense? @renz45 @katiedelfin

documentation request - what happens if there is an error?

can we assume that if there is a problem sending, then an error will be thrown?

I have tested for 'network down' and 'bad api key', but it would be great to get confirmation that this is always the case.

e.g. if I don't get an error, can I mark my email as successfully queued with mandril?

thanks.

Documentation: view_content_link bool or string?

Hi,

In the README, there is an example of using view_content_link with a string value, but Mandrill Mailer converts that argument to boolean. Does Mandrill accept a string or just a boolean?

Justin

Attachment Content

This is a stupid question, but I have looked everywhere for an answer.

What exactly does the attachment content need to be? I am using paperclip and I'm not totally sure what specific content (base64,etc.) we are supposed to pass in. Any help would be greatly appreciated

Update usage docs

There was some copy and pasting between the message mailer and template mailer when it comes to usage. These need to be rewritten to match all api attributes available.

undefined method `new' for API:Module

Hello, i installed the gem and set the enviroment, initializers and a new mailer as the README says, but I always get this error.

NoMethodError: undefined method new' for API:Module from /usr/local/rvm/gems/ruby-1.9.3-p448/gems/mandrill_mailer-0.4.4/lib/mandrill_mailer/template_mailer.rb:193:indeliver'

I don't know what could be? any suggestion? I'm using Rails 3.2 and Ruby 1.9.3

Thank u so much!

Wrong documentation in attachement

Hi there,

I just try to attache a document to my email.

I follow the home page guide :

  • :attachments - An array of file objects with the following keys:
    • content: The file contents, must be a base64 encoded string
    • name: The name of the file
    • type: This is the mimetype of the file. Ex. png = image/png, pdf = application/pdf, txt = text/plain etc etc

But I get this error :

Minitest::UnexpectedError: TypeError: no implicit conversion of nil into String

Then I check to code and see the documentation in the homepage looks wrong :
https://github.com/renz45/mandrill_mailer/blob/master/lib/mandrill_mailer/core_mailer.rb#L30
https://github.com/renz45/mandrill_mailer/blob/master/lib/mandrill_mailer/core_mailer.rb#L69
https://github.com/renz45/mandrill_mailer/blob/master/lib/mandrill_mailer/core_mailer.rb#L256

I think it could be cool to fix it ;)

mailchimp gem version 0.0.7.alpha

It looks like to get this gem to run I need mailchimp gem installed, however, it is locked to version =0.0.7.alpha . I was going to update the dependency for .9 but I can't find it in your code where it is declared?

undefined method '[]' for nil:NilClass when no defaults specified

perhaps similar to #77

With the following code:

class MyMailer < MandrillMailer::TemplateMailer

  def csv opts = {}
    new_lead_count = opts[:new_lead_count]

    yesterday = Date.yesterday.strftime('%Y-%m-%d')

    mandrill_mail(
      template: 'new-activity-report',
      subject: "New Activity summary for #{yesterday}",
      to: '[email protected]',
      from: '[email protected]',
      vars: {
        'DATE' => yesterday,
        'NEW_LEAD_COUNT' => new_lead_count
      }
     )
  end
end

I get the following error:

NoMethodError: undefined method `[]' for nil:NilClass
/Users/desmond/.gem/ruby/2.1.2/gems/mandrill_mailer-0.6.0/lib/mandrill_mailer/core_mailer.rb:346:in `merge_default_merge_vars'
/Users/desmond/.gem/ruby/2.1.2/gems/mandrill_mailer-0.6.0/lib/mandrill_mailer/core_mailer.rb:329:in `mandrill_args'
/Users/desmond/.gem/ruby/2.1.2/gems/mandrill_mailer-0.6.0/lib/mandrill_mailer/template_mailer.rb:162:in `mandrill_mail'
/Users/desmond/code/my_app/app/mailers/my_mailer.rb:29:in `csv'
/Users/desmond/.gem/ruby/2.1.2/gems/mandrill_mailer-0.6.0/lib/mandrill_mailer/core_mailer.rb:288:in `call'
/Users/desmond/.gem/ruby/2.1.2/gems/mandrill_mailer-0.6.0/lib/mandrill_mailer/core_mailer.rb:288:in `method_missing'
/Users/desmond/code/my_app/app/events/create_csv_report.rb:21:in `strategy'
/Users/desmond/.gem/ruby/2.1.2/bundler/gems/happenings-05d2bdcc2e15/lib/happenings/event.rb:20:in `block in run!'
/Users/desmond/.gem/ruby/2.1.2/bundler/gems/happenings-05d2bdcc2e15/lib/happenings/event.rb:99:in `time'
/Users/desmond/.gem/ruby/2.1.2/bundler/gems/happenings-05d2bdcc2e15/lib/happenings/event.rb:19:in `run!'

Adding default from: '[email protected]' fixes it. It seems I need at least one default option at the class level, or the @defaults var never gets set in MandrillMailer::CoreMailer. Maybe specify in the docs that calling .default is required?

Using on my development machine

Hi there,

Thanks so much for this awesome gem. I've had some great success so far with sending Mandrill templated mails.

I was just wondering if there is any way to run this in 'development' mode similarly to the Rails Mailers where it logs to the console if a mail would've been sent.

I'm currently stopping the MandrillMailer from sending a mail by including: 'require 'mandrill_mailer/offline'' at the top of my development.rb environment file, but it would be great to see if a mail would've been sent.

Thanks,
Ian

Delayed Job error - Insecure: can't modify instance variable with

Hi,

When I try to send an email using mandrill from a worker process I get the following error: Insecure: can't modify instance variable.

To clarify:
I have a method called user_joined, that calls mandrill_mail . I call it friend_joined delayed jobs:
user.delay.friend_joined .

When a Delayed Jobs works tried to execute the call, I get the above error.

Thanks!

Can't send mail without template

Hi, i'm calling it like this
mandrill_mail subject: subject,
to: '[email protected]',
text: 'some text',
html: '

some html

',
from: '[email protected]',
from_name: 'me',
bcc: nil,
important: true,
inline_css: true

And it returns
Mandrill::ValidationError: Validation error: {"template_name":"Sorry, this field can't be left blank."}

Config error!

I have an error when i add this line to mail.rb in initializers:

MandrillMailer.api_key = ENV['MANDRILL_API_KEY']

Error:

*** Exception NoMethodError in PhusionPassenger::Rack::ApplicationSpawner (undefined method `api_key=' for MandrillMailer:Module)

How to catch rejected mail reason?

Hi,

Sometimes the Mandrill API returns the status as rejected. What's the best way for me to detect this (or any other status) in the API response in my app? Specifically I would like to catch those situations and report it to my exception tracker.

Here is an example API response:

[
    {
        "email": "[email protected]",
        "status": "rejected",
        "_id": "SOME_ID",
        "reject_reason": "invalid-sender"
    }
]

I'm using the template mailer in a Rails app.

Any ideas? Thanks :-)

mailer.data raises NoMethodError after 1.0 upgrade

We have the following from_matcher on Code School which was calling the following:

# ...
def mailer_from_email(mailer)
    mailer.data['message']['from_email']
  end

  def mailer_from_name(mailer)
    mailer.data['message']['from_name']
  end
end

The calls to mailer.data used to succeed prior to 1.0 but no longer work. It seems like swapping them out for mailer.message["from_email"] and mailer.message["from_name"] works fine.

I'm just documenting this here for people who might encounter the same issue with their existing RSpec matchers.

Specifying "subaccount" doesn't seem to work

I'm trying to assign an email to a subaccount in Mandrill when sending a mail template. I couldn't see this in the documentation but in the source code for mandrill_mailer it looks like this should just be passed as another argument to the mandrill_mail method.

However it doesn't seem to be working, my subaccount in Mandrill shows no emails/activity attached even though the email was sent successfully.

I'm basically just calling it like this:

mandrill_mail template: 'my-template',
              subject: 'subject here',
              to: recipients,
              subaccount: 'my-subaccount-id'

Is this correct?

reusing an ActionMailer html.erb file

I can set content for a given template with:
template_content: {template_content_name => template_content_content},
( where template_content_name = 'std_content00' and template_content_content = 'Hello from the Mandrill API my email content!')

But how do I set template_content_content to an html.erb file, like a revised version of a user_mailer file?

undefined method `[]' for nil:NilClass

mailers/panel_mailer.rb

class PanelMailer < MandrillMailer::TemplateMailer

def blast(user, template)
humans = user.humans
mandrill_mail(
template: 'blast-1',
subject: template.subject,
to: [
{ email: "[email protected]", name: "Callum Short" }
],
vars: {
'BG_COLOUR' => "##{user.bghex}",
'LOGO' => user.logourl_url
},
template_content: {'body' => template.body},
inline_css: true,
preserve_recipients: true,
recipient_vars: [{"[email protected]" => {'FULL_NAME' => "Callum Short"}}]
)
end
end

Any ideas what's going wrong here? I get the error when triggering the mailer via a create action.

Running acceptance tests that use Mandrill Mailer

Just wondering what the recommended approach is for handling emails that are sent via Mandrill through acceptance tests/specs? Currently I'm not setting a valid API key, and so an exception gets raised... but I don't want to be talking to Mandrill when I run my tests.

I guess I could use something like VCR, but would it be better to look to Rails' ActionMailer settings (e.g. delivery_method == :test or raise_delivery_errors == false)? I'm happy to submit a patch for the latter if you think it's worthwhile.

License missing from gemspec

Some companies will only use gems with a certain license.
The canonical and easy way to check is via the gemspec,

via e.g.

spec.license = 'MIT'
# or
spec.licenses = ['MIT', 'GPL-2']

Even for projects that already specify a license, including a license in your gemspec is a good practice, since it is easily
discoverable there without having to check the readme or for a license file. For example, it is the field that rubygems.org uses to display a gem's license.

For example, there is a License Finder gem to help companies ensure all gems they use
meet their licensing needs. This tool depends on license information being available in the gemspec. This is an important enough
issue that even Bundler now generates gems with a default 'MIT' license.

If you need help choosing a license (sorry, I haven't checked your readme or looked for a license file), github has created a license picker tool.

In case you're wondering how I found you and why I made this issue, it's because I'm collecting stats on gems (I was originally looking for download data) and decided to collect license metadata,too, and make issues for gemspecs not specifying a license as a public service :).

I hope you'll consider specifying a license in your gemspec. If not, please just close the issue and let me know. In either case, I'll follow up. Thanks!

p.s. I've written a blog post about this project

Emails rejected - reject reason: Unsigned

I am using mandrill_mailer (1.1.0):

mandrill_mailer (1.1.0)
      mandrill-api (~> 1.0.9)

All of my emails are rejecting with status

Reject reason: Unsigned

outbound activity mandrill

Not sure, how to fix this issue and what is the exact cause.

Gem dependency conflict

Hi,

I get the following error on bundle update
Bundler could not find compatible versions for gem "excon":
In Gemfile:
mandrill_mailer (> 0.3.2) ruby depends on
excon (
> 0.15.4) ruby

asset_sync (>= 0) ruby depends on                                                                                                                                                           
  excon (0.16.2)                                                                                                                                                                            

Bundler could not find compatible versions for gem "tilt":
In Gemfile:
rails (= 3.2.0) ruby depends on
tilt (!= 1.3.0, ~> 1.1) ruby

sass-rails (>= 0) ruby depends on                                                                                                                                                           
  tilt (1.3)     

Any help would be appreciated!

Interceptor BCC addresses are not working

Hi,

I would like to use the interceptor_params to create a BCC recipient (or more than one BCC recipient) for all messages sent, but I would like the original recipient to still receive the message. If I set interceptor_params = {to: {email: "[email protected]", type: "bcc"}} then only the copy is sent, not the original.

I tried the following, and it doesn't send a copy:

config.interceptor_params = {bcc: {email: "[email protected]"}}

I also tried the following, based on the Mandrill API docs:

config.interceptor_params = {bcc_address: "[email protected]"}

No luck with that, either. Only the original email is sent out.

Any solutions? Is this a Mandrill_Mailer issue, or a Mandrill API issue, or a misconfiguration on my part?

TypeError when no merge vars are sent to mandrill_mail

I've identified a regression caused by my recent PR (#72).

When calling mandrill_mail without merge vars like:

mandrill_mail template: 'Expiration Post',
                    subject: "Blabla",
                    to: { email: options[:email], name: options[:name] }

mandrill_args is called with nil in TemplateMailer#mandrill_mail

mandrill_args attempts to call merge_default_merge_vars with nil in CoreMailer#mandrill_args.

Which finally explodes in CoreMailer#merge_default_merge_vars when we call:

self.class.defaults[:merge_vars].merge(args)

Because args == nil And {}.merge(nil) triggers a type error.

The solution I see is to do this:

def merge_default_merge_vars(args)
  return self.class.defaults[:merge_vars] unless args
  self.class.defaults[:merge_vars].merge(args)
end

Does that make sense @renz45?

Regarding Support for Rails Version 2.3.8

Hi,

I am planning to use mandrill_mailer for rails application 2.3.8. Its not supporting Could you please let me know the best way how can I use this gem for rails 2.3.8

Improperly declared runtime dependency to 'mandrill-api'

This one made me sweat a bit, but I finally figured it out.

In a Rails app (which you know ๐Ÿ˜‰) I created the following Mailer:

# in app/mailers/devise_mailer_router.rb

# See https://github.com/plataformatec/devise/wiki/How-To:-Use-custom-mailer
class DeviseMailerRouter < Devise::Mailer
  helper :application # gives access to all helpers defined within `application_helper`.
  include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url`

  def reset_password_instructions(record, token, opts={})
    # @token = token
    # devise_mail(record, :reset_password_instructions, opts)
    DeviseMailer.new.reset_password_instructions(record, token).deliver
  end
end

DeviseMailer inherits from MandrillMailer < TemplateMailer and looks like this:

class DeviseMailer < MandrillMailer::TemplateMailer
  default from: '[email protected]'

  def reset_password_instructions(user, token)
    mandrill_mail template: 'Password Request',
                  subject: 'Password Recovery',
                  from_name: 'Test',
                  to: { email: user.email, name: user.name },
                  vars: {
                    'PASSWORD_RESET_URL' => edit_user_password_url(user, :reset_password_token => token)
                  }
  end

  test_setup_for :reset_password_instructions do |mailer, options|
    user = User.new(email: options[:email],
                    username: 'foobar',
                    reset_password_token: rand(900000..1000000) )

    mailer.reset_password_instructions(user, token).deliver
  end

end

Whenever I loaded the view/controller that called DeviseMailerRouter.reset_password_instructions, the following error would happen:

LoadError:
       cannot load such file -- mandrill

Eventually I figured out that you declared mandrill-api as a dependency in your gemspec but not a runtime dependency, which concretely meant that, since it's not explicitly required inside of TemplateMailer, it's... not accessible outside the gem. I'm not really sure what the deal is but you get the idea.

PR Incoming.

Interceptor params ignored when mailer is executed from the console

I have an interceptor in place to keep the emails getting sent to real users' emails. This works great on our dev and staging environments. However, when generating an email locally from the rails console, the interceptor does not intercept and the email ends up actually getting delivered to the email from the DB and not from the interceptor.

The work around is to pass a proc as the interceptor instead of setting the interceptor_params.

Here is our mailer config file:

MandrillMailer.configure do |config|
  config.api_key = ENV['MANDRILL_APIKEY']
  unless Rails.env.production?
    # This was our existing setup that did not intercept when executing from the console
    # config.interceptor_params = {to: [{ email: ENV['INTERCEPTING_RECIPIENT'] }] }

    # This works on dev, staging, and from the console
    config.interceptor = Proc.new {|obj| obj[:to] = [{email: ENV['INTERCEPTING_RECIPIENT']}] }
  end
end

documentation not correct for interceptor_params

The configuration at the bottom of the readme didn't work with mandrill_mail and a template.

Here's my model:

class UserMailer < MandrillMailer::TemplateMailer
    def welcome (user)
      mandrill_mail template: 'awaiting-approval',
        to: {email: user.email, name: user.name},
        vars: {
          'FIRST_NAME' => user.first_name
        },
        important: true,
        inline_css: true,
        async: true
    end

end

I ended up doing it like so:

MandrillMailer.configure do |config|
    config.interceptor_params = { to: [email: '[email protected]', name: 'Homer Simpson'] }
end

If no vars are specified, the mailer breaks.

When using mandrill_mailer, if no vars are specified, an error occurs. Rather than requiring vars (vars is not specified as "Required" in the documentation like some of the other fields are), it should either be optional or specified as required in the doc. vars: {} can be used, but it would make sense to leave it out entirely when they're not needed, or to--again--specify that it is required (at least a blank vars is required). The exact line it breaks is:

Vendor/bundle/ruby/1.9.1/gems/mandrill_mailer-0.3.2/lib/mandrill_mailer/template_mailer.rb:288

And the error is:

NoMethodError: undefined method `map' for nil:NilClass

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.