Skip to content

Electron-libre/mailjet-gem

 
 

Repository files navigation

Mailjet

Mailjet's official Ruby wrapper, bootstraped with Mailjetter.

This gem helps you to:

  • Send transactional emails through Mailjet API in Rails 3/4
  • Manage your lists, contacts and campaigns, and much more...
  • Track email delivery through event API

Compatibility:

  • Ruby 1.9.X
  • Ruby 2.X.X

Rails ActionMailer integration designed for Rails 3.X and 4.X

IMPORTANT: Mailjet gem switched to API v3, the new API provided by Mailjet. For the wrapper for API v1, check the v1 branch.

Install

Bundler

Add the following in your Gemfile:

# Gemfile
gem 'mailjet'

If you wish to use the most up to date version from Github, add the following in your Gemfile instead:

#Gemfile
gem 'mailjet', :git => 'https://github.com/mailjet/mailjet-gem.git'

and let the bundler magic happen

$ bundle install

Rubygems

$ gem install mailjet

Setup

Api key

You need a proper account with Mailjet. You can get the API key through the Mailjet interface in Account/Master API key

Add the keys to an initializer:

# initializers/mailjet.rb
Mailjet.configure do |config|
  config.api_key = 'your-api-key'
  config.secret_key = 'your-secret-key'
  config.default_from = '[email protected]'
end

domain is needed if you send emails with :mailjet's SMTP (below)

default_from is optional if you send emails with :mailjet's SMTP (below)

Send emails with ActionMailer

As easy as:

# application.rb
config.action_mailer.delivery_method = :mailjet

Or if you prefer sending messages through mailjet REST API:

# application.rb
config.action_mailer.delivery_method = :mailjet_api

You can use mailjet specific options with delivery_method_options as detailed in the official ActionMailer doc

Manage your campaigns

This gem provide a convenient wrapper for consuming the mailjet API. The wrapper is highly inspired by ActiveResource even though it does not depend on it.

You can find out all the resources you can access to in the [Official API docs][apidocs].

Let's have a look at the power of this thin wrapper

Naming conventions

  • Class names' first letter is capitalized followed by the rest of the resource name in lowercase (e.g. listrecipient will be Listrecipient in ruby)
  • Ruby attribute names are the underscored versions of API attributes names (e.g. IsActive will be is_active in ruby)

Wrapper REST API

Let's say we want to manage list recipients.

GET all the recipients in one query:

> recipients = Mailjet::Listrecipient.all(limit: 0)
=> [#<Mailjet::Listrecipient>, #<Mailjet::Listrecipient>]

By default, .all will retrieve only 10 resources, so, you have to specify limit: 0 if you want to GET them all.

You can refine queries using API Filters* as well as the following parameters:

  • format: :json, :xml, :rawxml, :html, :csv or :phpserialized (default: :json)
  • limit: int (default: 10)
  • offset: int (default: 0)
  • sort: [[:property, :asc], [:property, :desc]]

GET the resources count

> Mailjet::Listrecipient.count
=> 83

GET the first resource matching a query

> Mailjet::Listrecipient.first
=> #<Mailjet::Listrecipient>

GET a resource from its id

> recipient = Mailjet::Listrecipient.find(id)
=> #<Mailjet::Listrecipient>

Updating a resource

> recipient = Mailjet::Listrecipient.first
=> #<Mailjet::Listrecipient>
> recipient.is_active = false
=> false
> recipient.attributes
=> {...} # attributes hash
> recipient.save
=> true
> recipient.update_attributes(is_active: true)
=> true

Deleting a resource

> recipient = Mailjet::Listrecipient.first
=> #<Mailjet::Listrecipient>
> recipient.delete
> Mailjet::Listrecipient.delete(123)
=> #<Mailjet::Listrecipient>

Send emails through API

In order to send emails through the API, you just have to create a new MessageDelivery resource.

Mailjet::MessageDelivery.create(from: "[email protected]", to: "[email protected]", subject: "Mailjet is awesome", text: "Yes, it is!")

If you want to send it to multiple recipients, just use an array:

Mailjet::MessageDelivery.create(from: "[email protected]", to: ["[email protected]", "[email protected]"], subject: "Mailjet is awesome", text: "Yes, it is!")

In order to Mailjet modifiers, you cannot use the regular form of Ruby 2 hashes. Instead, use a String e.g.: 'mj-prio' => 2 or a quoted symbol e.g.: 'mj-prio' => 2.

You can check available params in the official doc.

Track email delivery

You can setup your Rack application in order to receive feedback on emails you sent (clicks, etc.)

First notify Mailjet of your desired endpoint (say: 'http://www.my_domain.com/mailjet/callback') at https://www.mailjet.com/account/triggers

Then configure Mailjet's Rack application to catch these callbacks.

A typical Rails/ActiveRecord installation would look like that:

# application.rb

config.middleware.use Mailjet::Rack::Endpoint, '/mailjet/callback' do |params|  # using the same URL you just set in Mailjet's administration

  email = params['email'].presence || params['original_address'] # original_address is for typofix events

  if user = User.find_by_email(email)
    user.process_email_callback(params)
  else
    Rails.logger.fatal "[Mailjet] User not found: #{email} -- DUMP #{params.inspect}"
  end
end

# user.rb
class User < ActiveRecord::Base

  def process_email_callback(params)

    # Returned events and options are described at https://eu.mailjet.com/docs/event_tracking
    case params['event']
    when 'open'
      # Mailjet's invisible pixel was downloaded: user allowed for images to be seen
    when 'click'
      # a link (tracked by Mailjet) was clicked
    when 'bounce'
      # is user's email valid? Recipient not found
    when 'spam'
      # gateway or user flagged you
    when 'blocked'
      # gateway or user blocked you
    when 'typofix'
      # email routed from params['original_address'] to params['new_address']
    else
      Rails.logger.fatal "[Mailjet] Unknown event #{params['event']} for User #{self.inspect} -- DUMP #{params.inspect}"
    end
  end

Note that since it's a Rack application, any Ruby Rack framework (say: Sinatra, Padrino, etc.) is compatible.

Testing

For maximum reliability, the gem is tested against Mailjet's server for some parts, which means that valid credentials are needed. Do NOT use your production account (create a new one if needed), because some tests are destructive.

# GEM_ROOT/config.yml
mailjet:
  api_key: YOUR_API_KEY
  secret_key: YOUR_SECRET_KEY
  default_from: YOUR_REGISTERED_SENDER_EMAIL # the email you used to create the account should do it

Then at the root of the gem, simply run:

bundle
bundle exec rake

Send a pull request

  • Fork the project.
  • Create a topic branch.
  • Implement your feature or bug fix.
  • Add documentation for your feature or bug fix.
  • Add specs for your feature or bug fix.
  • Commit and push your changes.
  • Submit a pull request. Please do not include changes to the gemspec, or version file.

About

[API v3] Mailjet official Ruby GEM

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Ruby 100.0%