Giter Site home page Giter Site logo

mailjet-gem's Introduction

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

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

Send emails with ActionMailer

A quick walkthrough to using Action Mailer from the documentation HERE

First set your delivery method:

# application.rb or config/environments specific settings, which take precedence
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

Creating a Mailer:

$ rails generate mailer UserMailer

create  app/mailers/user_mailer.rb
create  app/mailers/application_mailer.rb
invoke  erb
create    app/views/user_mailer
create    app/views/layouts/mailer.text.erb
create    app/views/layouts/mailer.html.erb
invoke  test_unit
create    test/mailers/user_mailer_test.rb
create    test/mailers/previews/user_mailer_preview.rb

In the UserMailer class you can set up your email method:

#app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
  def welcome_email()
     mail(from: "[email protected]", to: "[email protected]",
          subject: "This is a nice welcome email")
   end
end

There's also the ability to set Mailjet custom headers

#app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
  def welcome_email()
      mail.header['X-MJ-CustomID'] = 'custom value'
      mail.header['X-MJ-EventPayload'] = 'custom payload'
    mail(from: "[email protected]", to: "[email protected]",
          subject: "This is a nice welcome email")
  end
end

For sending email, you can call the method with a variety of MessageDelivery priorities:

#In this example, we are sending immediately
UserMailer.welcome_email.deliver_now!

For more information on ActionMailer::MessageDeilvery, see the documentation HERE

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.

In these modifiers, there is now the ability to add a Mailjet custom-id or Mailjet Custom payload using the following:

'mj-customid' => "A useful custom ID"
'mj-eventpayload' => '{"message": "hello world"}'

For more information on custom properties and available params, see 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.

mailjet-gem's People

Contributors

tylerjnap avatar jbescoyez avatar bbenezech avatar swooop avatar 3367894 avatar mimmovele avatar electron-libre avatar gormador avatar skelz0r avatar avbrychak avatar germandz avatar omarqureshi avatar robink avatar

Watchers

James Cloos avatar  avatar moonpeople avatar

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.