The official Ruby wrapper for the Mailjet API is published as the mailjet gem and developed at mailjet/mailjet-gem.
- Ruby 2.2.x or higher
- The ActionMailer integration targets Rails >= 5
gem install mailjet# Gemfile
gem 'mailjet'To track the latest commit on GitHub instead of a released version:
# Gemfile
gem 'mailjet', :git => 'https://github.com/mailjet/mailjet-gem.git'Then:
bundle installConfigure the gem in an initializer:
# config/initializers/mailjet.rb
Mailjet.configure do |config|
config.api_key = ENV['MJ_APIKEY_PUBLIC']
config.secret_key = ENV['MJ_APIKEY_PRIVATE']
config.default_from = 'my_registered_sender@example.com'
endOn Rails you can generate the initializer:
rails generate mailjet:initializerdefault_from is optional when you send through Mailjet's SMTP relay with ActionMailer.
require 'mailjet'
Mailjet.configure do |config|
config.api_key = ENV['MJ_APIKEY_PUBLIC']
config.secret_key = ENV['MJ_APIKEY_PRIVATE']
config.api_version = 'v3.1'
end
response = Mailjet::Send.create(messages: [{
'From' => {
'Email' => 'pilot@example.com',
'Name' => 'Mailjet Pilot'
},
'To' => [
{
'Email' => 'passenger@example.com',
'Name' => 'Passenger 1'
}
],
'Subject' => 'My first Mailjet Email!',
'TextPart' => 'Greetings from Mailjet!',
'HTMLPart' => '<h3>Dear passenger 1, welcome to Mailjet!</h3>'
}])
p response.attributes[:messages]| Version | Scope |
|---|---|
v3 | Email API |
v3.1 | Send API v3.1 (latest send version) |
v4 | SMS API — not yet supported by this library |
Most Email API endpoints sit under v3, which is the default. For anything else, set api_version:
Mailjet.configure do |config|
config.api_key = ENV['MJ_APIKEY_PUBLIC']
config.secret_key = ENV['MJ_APIKEY_PRIVATE']
config.api_version = 'v3.1'
endThe default base domain is https://api.mailjet.com. Override it with end_point:
Mailjet.configure do |config|
config.api_key = ENV['MJ_APIKEY_PUBLIC']
config.secret_key = ENV['MJ_APIKEY_PRIVATE']
config.api_version = 'v3.1'
config.end_point = 'https://api.us.mailjet.com'
endAccounts on Mailjet's US architecture must set https://api.us.mailjet.com.
The gem follows Ruby conventions rather than the API's casing:
- Class names capitalise only the first letter of the resource name —
listrecipientbecomesMailjet::Listrecipient. - Attribute names are the underscored form of the API property —
IsActivebecomesis_active. - Action endpoints join resource and action with an underscore —
/contact/{id}/managecontactslistsbecomesMailjet::Contact_managecontactslists.
The full resource list is in /lib/mailjet/resources.
contact = Mailjet::Contact.create(email: 'passenger@example.com')
p contact.attributes['Data']Use id to identify the object the action applies to:
result = Mailjet::Contact_managecontactslists.create(id: contact_id, contacts_lists: [
{
'ListID' => list_id_1,
'Action' => 'addnoforce'
},
{
'ListID' => list_id_2,
'Action' => 'addforce'
}
])
p result.attributes['Data'].all returns 10 objects by default. Pass limit: 0 to retrieve everything, up to 1000 objects.
recipients = Mailjet::Listrecipient.all(limit: 0)Queries accept API filters plus these parameters:
| Parameter | Values | Default |
|---|---|---|
format | :json, :xml, :rawxml, :html, :csv, :phpserialized | :json |
limit | integer | 10 |
offset | integer | 0 |
sort | [[:property, :asc], [:property, :desc]] | — |
# all contacts in contact list 123
contacts = Mailjet::Contact.all(limit: 0, contacts_list: 123)contact = Mailjet::Contact.find('passenger@example.com')
p contact.attributes['Data']Two convenience helpers are also available:
Mailjet::Contact.count
# => 83
Mailjet::Contact.first
# => #<Mailjet::Contact>A PUT in the Mailjet API behaves like a PATCH: only the properties you send are updated, and non-mandatory properties can be omitted.
recipient = Mailjet::Listrecipient.first
recipient.is_active = false
recipient.save
# or in one call
recipient.update_attributes(is_active: true)A successful DELETE returns 204 No Content with no response body.
recipient = Mailjet::Listrecipient.first
recipient.delete
# or by ID
Mailjet::Listrecipient.delete(123)Build the CSV in the format described in Manage contacts via CSV upload, then:
Mailjet::ContactslistCsv.send_data(contact_list_id, File.open('contacts.csv', 'r'))Mailjet::ContactPii.delete(contact_id)Set the delivery method to Mailjet's SMTP relay:
# application.rb, or a config/environments file
config.action_mailer.delivery_method = :mailjetOr send through the Send API instead:
# application.rb
config.action_mailer.delivery_method = :mailjet_apiMailjet-specific options are passed through delivery_method_options:
class AwesomeMailer < ApplicationMailer
def awesome_mail(user)
mail(
to: user.email,
delivery_method_options: { api_key: 'your-api-key', secret_key: 'your-secret-key' }
)
end
endTo use the latest Send API version, set it explicitly:
delivery_method_options: { version: 'v3.1' }Supported options:
# v3.1
:api_key, :secret_key, :'Priority', :'CustomCampaign', :'DeduplicateCampaign',
:'TemplateLanguage', :'TemplateErrorReporting', :'TemplateErrorDeliver',
:'TemplateID', :'TrackOpens', :'TrackClicks', :'CustomID', :'EventPayload',
:'Variables', :'Headers'
# v3
:recipients, :'mj-prio', :'mj-campaign', :'mj-deduplicatecampaign',
:'mj-templatelanguage', :'mj-templateerrorreporting', :'mj-templateerrordeliver',
:'mj-templateid', :'mj-trackopen', :'mj-trackclick', :'mj-customid',
:'mj-eventpayload', :vars, :headersAlternatively, set the Mailjet SMTP headers directly:
headers['X-MJ-CustomID'] = 'order-1001'
headers['X-MJ-EventPayload'] = 'custom payload'
headers['X-MJ-TemplateLanguage'] = 'true'rails generate mailer UserMailer# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
def welcome_email
headers['X-MJ-CustomID'] = 'welcome-email'
mail(
from: 'pilot@example.com',
to: 'passenger@example.com',
subject: 'This is a nice welcome email'
)
end
end<%# app/views/user_mailer/welcome_email.html.erb %>
Hello world in HTML!<%# app/views/user_mailer/welcome_email.text.erb %>
Hello world in plain text!UserMailer.welcome_email.deliver_now!See the Rails guides on ActionMailer and ActionMailer::MessageDelivery for the rest.
The gem ships a Rack endpoint that receives Mailjet event callbacks (opens, clicks, bounces and so on).
First register your endpoint URL under account triggers, then mount the middleware on the same path:
# application.rb
config.middleware.use Mailjet::Rack::Endpoint, '/mailjet/callback' do |params|
# original_address is set for typofix events
email = params['email'].presence || params['original_address']
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# app/models/user.rb
class User < ActiveRecord::Base
def process_email_callback(params)
case params['event']
when 'open'
# the tracking pixel was loaded — the recipient allowed images
when 'click'
# a tracked link was clicked
when 'bounce'
# recipient not found — is the address valid?
when 'spam'
# the gateway or the recipient flagged the message
when 'blocked'
# the gateway or the recipient blocked the sender
when 'typofix'
# rerouted from params['original_address'] to params['new_address']
else
Rails.logger.fatal "[Mailjet] Unknown event #{params['event']} -- DUMP #{params.inspect}"
end
end
endBecause this is a Rack application, any Rack-compatible framework works — Sinatra, Padrino and others.
Parts of the gem's test suite run against Mailjet's live servers, so valid credentials are required. Do not use a production account — some tests are destructive.
# GEM_ROOT/config.yml
mailjet:
api_key: YOUR_API_KEY
secret_key: YOUR_SECRET_KEY
default_from: YOUR_REGISTERED_SENDER_EMAILbundle
bundle exec rakeThe wrapper is open source. Fork the repository, branch, implement your fix or feature, add documentation and specs, and open a pull request at mailjet/mailjet-gem — without changes to the gemspec or the version file. Documentation improvements belong in the API documentation repo.