Giter Club home page Giter Club logo

mailjet-gem's Introduction

alt text

Official Mailjet Ruby wrapper

Build Status

Overview

This repository contains the official Ruby wrapper for the Mailjet API, bootstraped with Mailjetter.

Check out all the resources and Ruby code examples in the Offical Documentation.

Table of contents

Compatibility

This library requires Ruby v2.2.X.

The Rails ActionMailer integration is designed for Rails >= 5.

Installation

Rubygems

Use the below command to install the wrapper.

$ gem install mailjet

Bundler

Add the following in your Gemfile:

# Gemfile
gem 'mailjet'

If you wish to use the most recent release from Github, add the following in your Gemfile instead:

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

Then let the bundler magic happen:

$ bundle install

Authentication

The Mailjet Email API uses your API and Secret keys for authentication. Grab and save your Mailjet API credentials by adding them 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.

But if you are using Mailjet with Rails, you can simply generate it:

$ rails generate mailjet:initializer

Make your first call

Here's an example on how to send an email:

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
variable = Mailjet::Send.create(messages: [{
    'From'=> {
        'Email'=> '$SENDER_EMAIL',
        'Name'=> 'Me'
    },
    'To'=> [
        {
            'Email'=> '$RECIPIENT_EMAIL',
            'Name'=> 'You'
        }
    ],
    'Subject'=> 'My first Mailjet Email!',
    'TextPart'=> 'Greetings from Mailjet!',
    'HTMLPart'=> '<h3>Dear passenger 1, welcome to <a href=\'https://www.mailjet.com/\'>Mailjet</a>!</h3><br />May the delivery force be with you!'
}]
)
p variable.attributes[:messages]

Call Configuration Specifics

API Versioning

The Mailjet API is spread among three distinct versions:

  • v3 - The Email API
  • v3.1 - Email Send API v3.1, which is the latest version of our Send API
  • v4 - SMS API (not supported in this library yet)

Since most Email API endpoints are located under v3, it is set as the default one and does not need to be specified when making your request. For the others you need to specify the version using api_version. For example, if using Send API v3.1:

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

Base URL

The default base domain name for the Mailjet API is https://api.mailjet.com. You can modify this base URL by setting a value for end_point in your call:

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"
end

If your account has been moved to Mailjet's US architecture, the URL value you need to set is https://api.us.mailjet.com.

List of resources

You can find the list of all available resources for this library, as well as their configuration, in /lib/mailjet/resources.

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)

Request examples

POST Request

Use the create method of the Mailjet CLient (i.e. variable = Mailjet::$resource.create($params)).

$params will be a list of properties used in the request payload.

Simple POST request

# Create a new contact:
require 'mailjet'
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
end
variable = Mailjet::Contact.create(email: "[email protected]"
)
p variable.attributes['Data']

Using actions

Some APIs allow the use of action endpoints. To use them in this wrapper, the API endpoint is in the beginning, followed by an underscore, followed by the action you are performing - e.g. Contact_managecontactslists.

Use id to specify the ID you want to apply a POST request to (used in case of action on a resource).

# Manage the subscription status of a contact to multiple lists
require 'mailjet'
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
end
variable = Mailjet::Contact_managecontactslists.create(id: $ID, contacts_lists: [{
    'ListID'=> '$ListID_1',
    'Action'=> 'addnoforce'
}, {
    'ListID'=> '$ListID_2',
    'Action'=> 'addforce'
}]
)
p variable.attributes['Data']

GET request

Retrieve all objects

Use the .all method of the Mailjet CLient (i.e. Mailjet::$resource.all()) to retrieve all objects you are looking for. By default, .all will retrieve only 10 objects - you have to specify limit: 0 if you want to GET them all (up to 1000 objects).

> recipients = Mailjet::Listrecipient.all(limit: 0)

Use filtering

You can refine queries using API filters, as well as the following parameters:

  • format: :json, :xml, :rawxml, :html, :csv or :phpserialized (default: :json)
  • limit: integer (default: 10)
  • offset: integer (default: 0)
  • sort: [[:property, :asc], [:property, :desc]]
# To retrieve all contacts from contact list ID 123:
> variable = Mailjet::Contact.all(limit: 0, contacts_list: 123)

Retrieve a single object

Use the .find method to retrieve a specific object. Specify the ID of the object inside the parentheses.

# Retrieve a specific contact ID.
require 'mailjet'
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
end
variable = Mailjet::Contact.find($CONTACT_EMAIL)
p variable.attributes['Data']

Retrieve the count of objects matching the query

> Mailjet::Contact.count
=> 83

Retrieve the first object matching the query

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

PUT request

A PUT request in the Mailjet API will work as a PATCH request - the update will affect only the specified properties. The other properties of an existing resource will neither be modified, nor deleted. It also means that all non-mandatory properties can be omitted from your payload.

Here's an example of a PUT request:

> 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

DELETE request

Here's an example of a DELETE request:

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

Upon a successful DELETE request the response will not include a response body, but only a 204 No Content response code.

Send emails with ActionMailer

A quick walkthrough to use Rails Action Mailer here.

First set your delivery method (here Mailjet SMTP relay servers):

# application.rb or config/environments specific settings, which take precedence
config.action_mailer.delivery_method = :mailjet

Or if you prefer sending messages through Mailjet Send 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:

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
end

Keep in mind that to use the latest version of the Send API, you need to specify the version via delivery_method_options:

delivery_method_options: { version: 'v3.1' }

Other supported options are:

# For v3_1 API

* :api_key
* :secret_key
* :'Priority'
* :'CustomCampaign'
* :'DeduplicateCampaign'
* :'TemplateLanguage'
* :'TemplateErrorReporting'
* :'TemplateErrorDeliver'
* :'TemplateID'
* :'TrackOpens'
* :'TrackClicks'
* :'CustomID'
* :'EventPayload'
* :'Variables'
* :'Headers'

# For v3_0 API

* :recipients
* :'mj-prio'
* :'mj-campaign'
* :'mj-deduplicatecampaign'
* :'mj-templatelanguage'
* :'mj-templateerrorreporting'
* :'mj-templateerrordeliver'
* :'mj-templateid'
* :'mj-trackopen'
* :'mj-trackclick',
* :'mj-customid'
* :'mj-eventpayload'
* :vars
* :headers

Otherwise, you can pass the custom Mailjet SMTP headers directly:

headers['X-MJ-CustomID'] = 'rubyPR_Test_ID_1469790724'
headers['X-MJ-EventPayload'] = 'rubyPR_Test_Payload'
headers['X-MJ-TemplateLanguage'] = 'true'

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

Next, create your templates in the views folder:

#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!

There's also the ability to set Mailjet custom headers

#app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
  def welcome_email()
    headers['X-MJ-CustomID'] = 'custom value'
    headers['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:

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

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

Manage contacts via CSV Upload

Create the CSV content in a format compatible with the Mailjet API, see the documentation HERE

Mailjet::ContactslistCsv.send_data(ID_CONTACTLIST, File.open('some_csvdata.csv', 'r'))
Mailjet::ContactPii.delete(contact_ID)

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

Contribute

Mailjet loves developers. You can be part of this project!

This wrapper is a great introduction to the open source world, check out the code!

Feel free to ask anything, and contribute:

  • Fork the project.
  • Create a new branch.
  • Implement your feature or bug fix.
  • Add documentation for it.
  • 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.

If you have suggestions on how to improve the guides, please submit an issue in our Official API Documentation repo.

mailjet-gem's People

Contributors

alessani avatar andre-l-github avatar antonc27 avatar arnaudbreton avatar bbenezech avatar eboisgon avatar electron-libre avatar gormador avatar jbescoyez avatar jnunemaker avatar kemenaran avatar latanasov avatar lorel avatar mgrishko avatar mimmovele avatar mscoutermarsh avatar mskochev avatar neolyte avatar omarqureshi avatar retttro avatar robink avatar sedubois avatar skelz0r avatar swooop avatar tylerjnap avatar uesteibar avatar xab3r avatar zedalaye avatar zeefarmer avatar zhivko-mailjet 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  avatar

mailjet-gem's Issues

Error with ruby ruby 2.1.2p95

Hi,
I am getting the following error while sending email sing mailjet.
Net::SMTPAuthenticationError: 435 4.7.8 Error: authentication failed:

Contactdata trouble

Hi,
I'am experiencing some trouble with the Contactdata.
Basically for a property 'language' with value 'en', I wrote :

Mailjet::Contactdata.create(:contact_id => contact.id, :data => [{"Name" => "language", "Value" => "en"}])

but an error is raised:

Mailjet::ApiError: error 400 while sending #<RestClient::Resource:0x00000101f373a0 @url="https://api.mailjet.com/v3/REST/contactdata", @block=nil, @options={:public_operations=>[:get, :put, :post, :delete], :read_only=>nil, :user=>"xxxxxx", :password=>"xxxxxxx"}> to https://api.mailjet.com/v3/REST/contactdata with {"ContactId"=>1, "Data"=>[{"Name"=>"language", "Value"=>"en"}]}

"{ \"ErrorInfo\" : \"\", \"ErrorMessage\" : \"Invalid json input: property \\\"Data[Name]\\\" not found at stream position 34\", \"StatusCode\" : 400 }"

Perhaps there is a problem with the way data are sent to the API : I have seen that the gem is sending using "application/x-www-form-urlencoded" content type, whereas in the mailjet api example they use json. Obvioulsy, when I tried with curl using the request made with the lib (url encoded), I got the same error, but if I tried with curl with json doing

curl -s -X POST --user "xxxxx:xxxxx" https://api.mailjet.com/v3/REST/contactdata -H 'Content-Type: application/json' -d '{"ContactID": 1, "Data" : [{"Name" : "language", "Value" : "en"}]}'

and it worked perfectly, as well as if I directly use RestClient as below

r = RestClient::Resource.new(Mailjet.config.end_point+'/'+Mailjet::Contactdata.resource_path,Mailjet.config.api_key, Mailjet.config.secret_key)
r.post({"ContactId" => contact.id, "Data" => [{"Name" => "language", "Value" => "en"}]}.to_json, :content_type => :json)

Is there a known problem, and why the gem isn't using json?
Thanks

Not compatible with ruby 2.1.2

Because ruby 2.1.2 doesn't appear to allow 'string': value syntax, the gem doesn't work.

SyntaxError: .../shared/bundle/ruby/2.1.0/gems/mailjet-1.0.3/lib/mailjet/mailer.rb:47: syntax error, unexpected ':', expecting =>

'mj-customid': mail['X-MJ-CustomID'] && mai...

Luckily, I was able to upgrade to ruby 2.2.2 to resolve this.

Note: the documentation says that this gem is compatible with 2.x.x.

uninitialized constant Mailjet::Template

Hi,

I was checking the API docs for creating transactional templates (link)

So when executing Mailjet::Template.create(name: "First Template") I got the following error:
NameError: uninitialized constant Mailjet::Template

From the gem code it seems this resource isn't yet implemented.

Get the email ID of an email sent with ActionMailer

Hi,
I can't get the ID of an email sent with the delivery_method :mailjet_api.
In lib/mailjet/mailer.rb Mailjet::APIMailer .deliver!() you use the Mailjet::MessageDelivery.create() which return an object with an email ID but with ActionMailer I can't find a way to get it.
I would like to track some emails by their ids (with the middleware) instead of the email address because I track some specific emails.
Thanks,
Ugo

Ruby 2.2

Hi,

Since I updated ruby to 2.2 I have this error:

/home/user/.rbenv/versions/2.2.0/lib/ruby/gems/2.2.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:247:in `require': /home/user/.rbenv/versions/2.2.0/lib/ruby/gems/2.2.0/gems/mailjet-1.0.0/lib/mailjet/api_error.rb:14: syntax error, unexpected keyword_do_cond, expecting ':' (SyntaxError)
          [(res['errors'] || [])].flatten.map do |param, text|
                                                ^

Unable to update Newsletter_detailcontent

Hi everyone,

I'm trying to send a marketing campaign and am following the documentation.

First of all, my newsletter is not creating with a contact list, even though the ID I am inputing is valid.

Then, when I try to update Newsletter_detailcontent to add Html content, this issue is sent : NameError: undefined local variable or method `id' for #Mailjet::Newsletter_detailcontent:0x007ffb70a5a910

Here is my code :

    variable = Mailjet::Newsletter.create(locale: "en_US",sender: "Me",sender_email: "[email protected]",subject: "TEST",contacts_list_id: "$ID",title: "TEST CAMPAIGN")
    target = Mailjet::Newsletter_detailcontent.find(variable.id)
    target.update_attributes(html_part: "Hello <strong>world</strong>!",text_part: "Hello world!")
    test = Mailjet::Newsletter_send.create(id: variable.id)

Where am I mistaken ?

Also, what is the easiest way to add more "complex" html code as content instead of "one liners" like the hello world ?

Thanks !

Creating a new campaign

Code used -- not working for whatever reason:

require 'mailjet'

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

campaign = Mailjet::Campaign.create(title: "Friday newsletter", list_id: Mailjet::List.all.first.id, from: "[email protected]", from_name: "Bob Smith", subject: "My Friday newsletter", lang: "en", footer: "default")

Error Stack:

NoMethodError: undefined method `in?' for "1484316":String
    from /Users/tylernappy/.rvm/gems/ruby-2.0.0-p247/gems/mailjet-0.0.5/lib/mailjet/campaign.rb:63:in `block in find'
    from /Users/tylernappy/.rvm/gems/ruby-2.0.0-p247/gems/mailjet-0.0.5/lib/mailjet/campaign.rb:63:in `each'
    from /Users/tylernappy/.rvm/gems/ruby-2.0.0-p247/gems/mailjet-0.0.5/lib/mailjet/campaign.rb:63:in `find'
    from /Users/tylernappy/.rvm/gems/ruby-2.0.0-p247/gems/mailjet-0.0.5/lib/mailjet/campaign.rb:63:in `find'
    from /Users/tylernappy/.rvm/gems/ruby-2.0.0-p247/gems/mailjet-0.0.5/lib/mailjet/campaign.rb:50:in `create'
    from (irb):22
    from /Users/tylernappy/.rvm/rubies/ruby-2.0.0-p247/bin/irb:12:in `<main>

ActionMailer - From Name not being set

Hi,

Having issues when using action mailer with :mailjet_api. The from_name is not being set on emails we send.

I have this in my config settings.

 config.action_mailer.delivery_method = :mailjet_api
Mailjet.configure do |config|
  config.api_key = ..key..
  config.secret_key = ..key...
  config.default_from = 'My Name <[email protected]>'
end

But the name is not being set correctly in the from field for emails we send.

Emails are saying they are from "[email protected]", rather than "My Name"

Any ideas?

@GuillaumeBadi @eboisgon

Some default properties (like "Persisted") are rejected by Mailjet server API

lr = Mailjet::Listrecipient.first(:contacts_list => l.id, :contact =>  c.id)

puts "Unsubscribing ListRecipient ContactID=#{lr.contact_id}, ListID=#{lr.list_id}"

lr.is_active = false
lr.is_unsubscribed = true
lr.save!

causes this error "TListRecipient has no property Persisted"

/home/pierre/.rbenv/versions/2.2.4/lib/ruby/gems/2.2.0/gems/mailjet-1.3.6/lib/mailjet/connection.rb:83:in `handle_exception': error 400 while sending #<RestClient::Resource:0x0055ef6864d1f8 @url="https://api.mailjet.com/v3/REST/listrecipient/313618576", @block=nil, @options={:public_operations=>[:get, :put, :post, :delete], :read_only=>nil, :user=>"adf02d8564c80d85d4c658d32ae796af", :password=>"31f35093742fc5eeda64f7f70585eda6", :content_type=>"application/json"}> to https://api.mailjet.com/v3/REST/listrecipient/313618576 with {"Persisted"=>true, "ContactId"=>1, "Id"=>313618576, "IsUnsubscribed"=>true, "ListId"=>1486932, "ListName"=>"Newsletter"} (Mailjet::ApiError)
**
"{ \"ErrorInfo\" : \"\", \"ErrorMessage\" : \"Invalid json input: object \\\"\\\"->\\\"TListRecipient\\\" has no property \\\"Persisted\\\"\", \"StatusCode\" : 400 }"

I suspect this because of the "noresourceprops" change :

    def formatted_payload
      payload = attributes.reject { |k,v| v.blank? }
      # payload = payload.slice(*resourceprop)
      payload = camelcase_keys(payload)
      payload.inject({}) do |h, (k, v)|
        v = v.utc.as_json if v.respond_to? :utc
        h.merge!({k => v})
      end
    end

payload contains all Resource attributes including "Persisted" that is not filtered because of the removal of payload.slice(*resourceprop) line.

Inconsistency on contact data depending on the method being called.

Very hard to find a real coherence in your api.

Mailjet::Contact.find("[email protected]")

tells me the id is an email :

#<Mailjet::Contact:0x007f969f151b38 @attributes={
"persisted"=>true,
"created_at"=>Thu, 28 Jan 2016 09:07:10 +0000,
 "delivered_count"=>1,
"email"=>"[email protected]",
"exclusion_from_campaigns_updated_at"=>"",
"id"=>"[email protected]",
"is_excluded_from_campaigns"=>false,
"is_opt_in_pending"=>false,
"is_spam_complaining"=>false,
"last_activity_at"=>Tue, 01 Mar 2016 14:29:08 +0000
 "last_update_at"=>"",
"name"=>"",
"unsubscribed_at"=>""
 "unsubscribed_by"=>""}> 

Just to double check :

Mailjet::Contact.all.each do |c|
puts c.inspect
end; nil

tells me the id is numeric :

...
#<Mailjet::Contact:0x007f969cdb92e8 @attributes={
"persisted"=>true,
"created_at"=>Thu, 28 Jan 2016 09:07:10 +0000,
"delivered_count"=>1,
"email"=>"[email protected]",
"exclusion_from_campaigns_updated_at"=>"",
"id"=>14541765,
"is_excluded_from_campaigns"=>false,
"is_opt_in_pending"=>false,
"is_spam_complaining"=>false,
"last_activity_at"=>Tue, 01 Mar 2016 14:29:08 +0000,
"last_update_at"=>"",
"name"=>"",
"unsubscribed_at"=>"",
"unsubscribed_by"=>""}>
...

as developpers, what should your we think about the mailjet api ?

I was just trying to update some users data :
Mailjet::Contactdata.create(:contact_id => "[email protected]", :data => [ {"Name" => "subscribed", "Value" => true} ])

As you might understand, it breaks, as you require here a numeric id. How do i do a simple lookup by email that would returns me the USEFUL id ?

Emails not being sent when using templates

When using templates emails are not being sent

    message = { from_email: '[email protected]',
                subject: 'Confirmation instructions',
                'Mj-TemplateID' => 12345,
                'Mj-TemplateLanguage' => true,
                recipients: [{ email: '[email protected]', name: 'My name' }],
                vars: { myvar: 'some value' }
              }
    Mailjet::Send.create(message)

But if I remove this line 'Mj-TemplateLanguage' => true, the email is sent, but the variables are not being parsed.

allow accessing error data

I can see on the exception code that the api returns some more detailed json but - stop me if i'm wrong - we can't programmatically access it rescuing mallet exceptions as it's mixed with some other strings.

would it be possible to make it accessible?

sorry if it's not ruby specific but also it would be great to have standard codes for each errors on the api.

for example this error is not specific enough:

"{ "ErrorInfo" : "", "ErrorMessage" : "MJ18 A Contact resource with value \"[email protected]\" for Email already exists.", "StatusCode" : 400 }"

for now i will test for "Email already exists" presence but it's a really dirty hack. Accessing this json within exception rescuing and having something like ErrorCode: 'ExistingEmail' would be the perfect thing

Alexandre

GET user info by email

I have several contact lists and would like to request a user by email address within one of these lists. How would I do that ?

For now I do Mailjet::Contact.find(@user.email), but I'm not sure the user requested is in the right contact list.

Thank you !

Update Rubygem ?

Hi,

Great job for this gem, but in rubygems.org, the git version is not up to date. Since June 10, 2014 you fixed a bug 9f9b09c.

Do you think that you can update the rubygem version ?

Thanks,
Geoffrey

Contactslist_managecontact sending an error

Hello,

We've received a lot of emails from users in the past two days telling us that they can't verify their account and subscribe to our newsletter.

This is what I get in development :

error 401 while sending #<RestClient::Resource:0x007fb17730b030 @url="https://api.mailjet.com/v3/REST/contactslist/1450104/managecontact", @block=nil, @options={:public_operations=>[:post], :read_only=>nil, :user=>nil, :password=>nil, :content_type=>"application/json"}> to https://api.mailjet.com/v3/REST/contactslist/1450104/managecontact with {"Email"=>"[email protected]", "Action"=>"addforce"} "" Please see http://api.mailjet.com/0.1/HelpStatus for more informations on error numbers.

Here is my code:
Mailjet::Contactslist_managecontact.create(id: 1450104, action: "addforce", email: @email)

Can you please try to fix it as soon as possible ?

Thanks,

Julien

Email is not being sent if you dont provide the from_email

Although I have a default from email configured as https://github.com/mailjet/mailjet-gem#api-key, and I'm using a template which also already define a subject and an email from, if I do

email = { 
          'Mj-TemplateID' => 15023,
          :recipients   => [{:email => "[email protected]"}] }

test = Mailjet::Send.create(email)

I receive

=> #<Mailjet::Send:0x007f9d645557e0
 @attributes=
  {"persisted"=>false,
   "Mj-TemplateID"=>15023,
   "recipients"=>[{"email"=>"[email protected]"}],
   "Sent"=>[{"Email"=>"[email protected]", "MessageID"=>18295908240864304}]},
 @persisted=true>

Which I assume nothing is missing, because there was no error, but the email is not being sent. I have to explicitly set :from_email => "[email protected]".

Any clue why I have to set the from_email despite having it set in 2 different places?

Thanks

Rails 4.0 Compatibility

This gem seems incompatible with Rails 4.0 so far. Getting "Invalid delivery method: mailjet" error.

ruby syntax filters do not work properly

 Mailjet::Contact.all('ContactsList' => remote_list.id)
=> []

This sound ok because this list is empty, but with underscored syntax:

Mailjet::Contact.all(:contacts_list => remote_list.id)
=> [#<Mailjet::Contact:0x000000084b5818
  @attributes=
   {"persisted"=>true,
    "created_at"=>Tue, 26 May 2015 14:47:47 +0000,
    "delivered_count"=>0,
    "email"=>"[email protected]",
    "id"=>1,
    "is_opt_in_pending"=>false,
    "is_spam_complaining"=>false,
    "last_activity_at"=>Tue, 26 May 2015 14:47:47 +0000,
    "last_update_at"=>"",
    "name"=>"",
    "unsubscribed_at"=>"",
    "unsubscribed_by"=>""}>,
 #<Mailjet::Contact:0x000000084b46c0

It should be empty !

The first workaround could be to update filters documentation.
If I have enougth time I'll have a closer look to provide a fix.

Wrong API Version?

I tried some API calls with the version 1.0. I always get a 400 response.

After some debugging with curl, I receive a "HTTP/1.1 400 Wrong API version" with no body.

Is the API v3 usable?

http://dev.mailjet.com/guides Ruby examples dosen't match with the gem

I'm trying to send email with attachment through the api.

variable = Mailjet::Send.create(
        from_email: "[email protected]",
        from_name: "Mailjet Pilot",
        subject: "Your email flight plan!",
        text_part: "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        html_part: "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        recipients: [{'Email'=> '[email protected]'}],
    attachments: [{'Content-Type' => 'text/plain', 'Filename' => 'test.txt', 'content' => 'VGhpcyBpcyB5b3VyIGF0dGFjaGVkIGZpbGUhISEK'}])

The example in the gem say

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

But I don't know how to join an attachment.

And how can I add an attachment with mailjet api and ActionMailer.

attachments['file.txt'] = { mime_type: 'application/x-gzip', content: File.read('public/file.txt') }
mail to: email, subject: 'test'

The email is delivered without the attachment.

Can't access Mailjet::Listrecipient

Hi,

From the rails console, I can't use the API wrapper to follow the documentation :

[11] pry(main)> Mailjet::Listrecipient.all

Mailjet::ApiError: error 400 while sending #<RestClient::Resource:0x007fde06373b88 @url="https://api.mailjet.com//v3/REST/listrecipient", @block=nil, @options={:public_operations=>[:get, :put, :post, :delete], :read_only=>nil, :user=>"my_user_id", :password=>"my_private_key"}> to https://api.mailjet.com//v3/REST/listrecipient with {}

""

Please see http://api.mailjet.com/0.1/HelpStatus for more informations on error numbers.

And I don't know how I could be working as I hadn't specified my list ID ... ?!

I've install the gem, and of course Mailjet::Listrecipient is found by the console.

I've looked at #25 and

  • It should has been resolved

  • Even if I try the given answer, no luck ...

    My final goal is to add a subscription form, so I'd like to be able to do a Mailjet::Listrecipient.create(contact_id: '[email protected]', list_id: 12345) (which is not working as well).

Thanks,

Stan

Unable to use Mailjet::Listrecipient

The default Mailjet::Listrecipient API is not usable.

require 'mailjet'
require 'active_support/all'

Mailjet.configure do |config|
  config.api_key = 'xxxxx'
  config.secret_key = 'xxxxx'
end

c = Mailjet::Contact.all(limit: 0)
l = Mailjet::Contactslist.all(limit: 0)

Mailjet::ListRecipient.create(:contact =>  c.first.id, :list => l.first.id)

Returns the following error:

'handle_exeception': error 400 while sending #<RestClient::Resource:0x00000003f39730 @url="https://api.mailjet.com//v3/REST/listrecipient", @block=nil, @options={:public_operations=>[:get, :put, :post, :delete], :read_only=>nil, :user=>"xxxxx", :password=>"xxxxx"}> to https://api.mailjet.com//v3/REST/listrecipient with {"Contact"=>1, "List"=>1} (Mailjet::ApiError)

"{ \"ErrorInfo\" : \"\", \"ErrorMessage\" : \"Invalid json input: expected \\\",\\\", but found \\\"\\\"\\\" at stream position 15 ...ntact\\\" : \\\"|1\\\", \\\"List\\\"...\", \"StatusCode\" : 400 }"

Please see http://api.mailjet.com/0.1/HelpStatus for more informations on error numbers.

According to the official APIv3 documentation the Contact and List fields are both mandatory and requires respectively a ReadOnly (?!?) Type Contact and a Type List. These types are not documented.

I found a hint here : https://github.com/mailjet/wordpress-mailjet-plugin-apiv3/blob/master/wp-mailjet.php#L198

The mandatory fields seems to be ContactID and TypeID but those are not accessible with the Ruby API that filters properties based on symbols and according to the Naming Conventions, there is no way to write a symbol that will be turned into ContactID.

My workaround is to write a ListRecipient (note the capital R...) class that allows the ContactID and TypeID keys for params :

module Mailjet
  class ListRecipient
    include Mailjet::Resource
    self.resource_path = '/v3/REST/listrecipient'
    self.public_operations = [:get, :put, :post, :delete]
    self.filters = [:active, :blocked, :contact, :contact_email, :contacts_list, :last_activity_at, :list_name, :opened, :status, :unsub]
    self.properties = [:contact, :id, :is_active, :is_unsubscribed, :list, :unsubscribed_at, 'ContactID', 'ListID']
  end
end

and now, this code works as expected :

Mailjet::ListRecipient.create('ContactID' =>  c.first.id, 'ListID' => l.first.id)

Newsletter_detailcontent.find undefined local variable or method `id'

Hi everyone,

When I try to get contents of the newsletter, I receive the following error:

NameError: undefined local variable or method `id' for #<Mailjet::Newsletter_detailcontent:0x007f54f81cad50>
from /path-to-gem/mailjet-gem/lib/mailjet/resource.rb:310:in `method_missing'

Here is my code :

create_newsletter_param = {
  Locale: "ja_JP",
  Sender: "Me",
  SenderEmail: "[email protected]",
  Subject: "test mail",
  ContactsListID: list_id,
  Title: "Test campaign"
}
newsletter = Mailjet::Newsletter.create(create_newsletter_param)
content = Mailjet::Newsletter_detailcontent.find(newsletter.id)

Thanks!

Errors when sending emails.

When use smtp i get this:

Net::SMTPAuthenticationError (435 4.7.8 Error: authentication failed:)

When API

Mailjet::ApiError (error 400 while sending #<RestClient::Resource:0xb4c207e0 @url="https://api.mailjet.com/v3/send", @block=nil, @options={:public_operations=>[:post], :read_only=>nil, :user=>"07e29cf3275767538c69e9432a4d0888", :password=>"********************"}> to https://api.mailjet.com/v3/send with {}

Connecting with browser to api is OK...
PS: I'm using ActionMailer for sending emails...

Mailjet domain

Your README talks about setting a config for domain, however it actually throws an error if you try to set it

How to send email?

I want to send a test email, but there is no information on how to send emails...

Exception thrown when trying to find an inexisting resource

cl = Mailjet::Contactslist.find(42)

Instead of returning nil, raises an "unexpected end of file" exception

/home/pierre/.rvm/gems/ruby-2.1.2/gems/rest-client-1.7.2/lib/restclient/request.rb:504:in `read': unexpected end of file (Zlib::GzipFile::Error)
    from /home/pierre/.rvm/gems/ruby-2.1.2/gems/rest-client-1.7.2/lib/restclient/request.rb:504:in 'decode'
    from /home/pierre/.rvm/gems/ruby-2.1.2/gems/rest-client-1.7.2/lib/restclient/request.rb:489:in 'process_result'
    from /home/pierre/.rvm/gems/ruby-2.1.2/gems/rest-client-1.7.2/lib/restclient/request.rb:421:in 'block in transmit'
    from /home/pierre/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/net/http.rb:853:in `start'
    from /home/pierre/.rvm/gems/ruby-2.1.2/gems/rest-client-1.7.2/lib/restclient/request.rb:413:in 'transmit'
    from /home/pierre/.rvm/gems/ruby-2.1.2/gems/rest-client-1.7.2/lib/restclient/request.rb:176:in 'execute'
    from /home/pierre/.rvm/gems/ruby-2.1.2/gems/rest-client-1.7.2/lib/restclient/request.rb:41:in 'execute'
    from /home/pierre/.rvm/gems/ruby-2.1.2/gems/rest-client-1.7.2/lib/restclient/resource.rb:51:in 'get'
    from /home/pierre/.rvm/gems/ruby-2.1.2/gems/mailjet-1.0.0/lib/mailjet/connection.rb:47:in 'handle_api_call'
    from /home/pierre/.rvm/gems/ruby-2.1.2/gems/mailjet-1.0.0/lib/mailjet/connection.rb:26:in `get'
    from /home/pierre/.rvm/gems/ruby-2.1.2/gems/mailjet-1.0.0/lib/mailjet/resource.rb:52:in `find'
    from /home/pierre/Projets/ng/mailjet_test/test.rb:66:in `<top (required)>'
    from -e:1:in `load'
    from -e:1:in `<main>'

this gem feels bad.

Just look at the id your api returns, depending on which language you use

system("curl -s -X GET --user '#{ENV["MAILJET_API_KEY"]}:#{ENV["MAILJET_SECRET_KEY"]}' https://api.mailjet.com/v3/REST/contact/[email protected]")

returns :

{ "Count" : 1, "Data" : [{ "CreatedAt" : "2016-01-28T09:07:10Z", "DeliveredCount" : 1, "Email" : "[email protected]", "ExclusionFromCampaignsUpdatedAt" : "", "ID" : 14541765, "IsExcludedFromCampaigns" : false, "IsOptInPending" : false, "IsSpamComplaining" : false, "LastActivityAt" : "2016-03-01T14:29:08Z", "LastUpdateAt" : "", "Name" : "", "UnsubscribedAt" : "", "UnsubscribedBy" : "" }], "Total" : 1 } => true

Mailjet::Contact.find("[email protected]")

returns :

#<Mailjet::Contact:0x007f9698e5aae8 @attributes={"persisted"=>true, "created_at"=>Thu, 28 Jan 2016 09:07:10 +0000, "delivered_count"=>1, "email"=>"[email protected]", "exclusion_from_campaigns_updated_at"=>"", "id"=>"[email protected]", "is_excluded_from_campaigns"=>false, "is_opt_in_pending"=>false, "is_spam_complaining"=>false, "last_activity_at"=>Tue, 01 Mar 2016 14:29:08 +0000, "last_update_at"=>"", "name"=>"", "unsubscribed_at"=>"", "unsubscribed_by"=>""}> 

You'll tell me, the curl method is not the same as the ruby methodโ€ฆ no waitโ€ฆ the contact object differs from one language to another ? Wait no, there's multiple type of contact object ?

Error when deploying into Heroku

Hi,
i have configured the mailjet gem in my gem file as follows.
gem 'mailjet', :git => "[email protected]:mailjet/mailjet-gem.git", :branch => "v1"

When i psuh my code in to heroku i got following error.
Fetching [email protected]:mailjet/mailjet-gem.git
Host key verification failed.
fatal: The remote end hung up unexpectedly
Retrying git clone '[email protected]:mailjet/mailjet-gem.git' "/tmp/build_ad869f42-c1bf-4459-a88f-f138786b3b08/vendor/bundle/ruby/2.1.0/cache/bundler/git/mailjet-gem-eae8e383bb9c27a16b16224a07c6e1a7d0503c09" --bare --no-hardlinks --quiet due to error (2/3): Bundler::Source::Git::GitCommandError Git error: command git clone '[email protected]:mailjet/mailjet-gem.git' "/tmp/build_ad869f42-c1bf-4459-a88f-f138786b3b08/vendor/bundle/ruby/2.1.0/cache/bundler/git/mailjet-gem-eae8e383bb9c27a16b16224a07c6e1a7d0503c09" --bare --no-hardlinks --quiet in directory /tmp/build_ad869f42-c1bf-4459-a88f-f138786b3b08 has failed.
Host key verification failed.
fatal: The remote end hung up unexpectedly
Retrying git clone '[email protected]:mailjet/mailjet-gem.git' "/tmp/build_ad869f42-c1bf-4459-a88f-f138786b3b08/vendor/bundle/ruby/2.1.0/cache/bundler/git/mailjet-gem-eae8e383bb9c27a16b16224a07c6e1a7d0503c09" --bare --no-hardlinks --quiet due to error (3/3): Bundler::Source::Git::GitCommandError Git error: command git clone '[email protected]:mailjet/mailjet-gem.git' "/tmp/build_ad869f42-c1bf-4459-a88f-f138786b3b08/vendor/bundle/ruby/2.1.0/cache/bundler/git/mailjet-gem-eae8e383bb9c27a16b16224a07c6e1a7d0503c09" --bare --no-hardlinks --quiet in directory /tmp/build_ad869f42-c1bf-4459-a88f-f138786b3b08 has failed.
Host key verification failed.
fatal: The remote end hung up unexpectedly
Git error: command git clone '[email protected]:mailjet/mailjet-gem.git' "/tmp/build_ad869f42-c1bf-4459-a88f-f138786b3b08/vendor/bundle/ruby/2.1.0/cache/bundler/git/mailjet-gem-eae8e383bb9c27a16b16224a07c6e1a7d0503c09" --bare --no-hardlinks --quiet in directory
/tmp/build_ad869f42-c1bf-4459-a88f-f138786b3b08 has failed.
Bundler Output: Fetching source index from http://rubygems.org/
Updating git://github.com/rweng/jquery-datatables-rails.git
Fetching [email protected]:mailjet/mailjet-gem.git
Host key verification failed.
fatal: The remote end hung up unexpectedly
Retrying git clone '[email protected]:mailjet/mailjet-gem.git' "/tmp/build_ad869f42-c1bf-4459-a88f-f138786b3b08/vendor/bundle/ruby/2.1.0/cache/bundler/git/mailjet-gem-eae8e383bb9c27a16b16224a07c6e1a7d0503c09" --bare --no-hardlinks --quiet due to error (2/3): Bundler::Source::Git::GitCommandError Git error: command git clone '[email protected]:mailjet/mailjet-gem.git' "/tmp/build_ad869f42-c1bf-4459-a88f-f138786b3b08/vendor/bundle/ruby/2.1.0/cache/bundler/git/mailjet-gem-eae8e383bb9c27a16b16224a07c6e1a7d0503c09" --bare --no-hardlinks --quiet in directory /tmp/build_ad869f42-c1bf-4459-a88f-f138786b3b08 has failed.
Host key verification failed.
fatal: The remote end hung up unexpectedly
Retrying git clone '[email protected]:mailjet/mailjet-gem.git' "/tmp/build_ad869f42-c1bf-4459-a88f-f138786b3b08/vendor/bundle/ruby/2.1.0/cache/bundler/git/mailjet-gem-eae8e383bb9c27a16b16224a07c6e1a7d0503c09" --bare --no-hardlinks --quiet due to error (3/3): Bundler::Source::Git::GitCommandError Git error: command git clone '[email protected]:mailjet/mailjet-gem.git' "/tmp/build_ad869f42-c1bf-4459-a88f-f138786b3b08/vendor/bundle/ruby/2.1.0/cache/bundler/git/mailjet-gem-eae8e383bb9c27a16b16224a07c6e1a7d0503c09" --bare --no-hardlinks --quiet in directory /tmp/build_ad869f42-c1bf-4459-a88f-f138786b3b08 has failed.
Host key verification failed.
fatal: The remote end hung up unexpectedly
Git error: command git clone '[email protected]:mailjet/mailjet-gem.git' "/tmp/build_ad869f42-c1bf-4459-a88f-f138786b3b08/vendor/bundle/ruby/2.1.0/cache/bundler/git/mailjet-gem-eae8e383bb9c27a16b16224a07c6e1a7d0503c09" --bare --no-hardlinks --quiet in directory
/tmp/build_ad869f42-c1bf-4459-a88f-f138786b3b08 has failed.
!
! Failed to install gems via Bundler.
!

! Push rejected, failed to compile Ruby app

Newsletter_send.create error 400

Hi everyone,

When I try to send newsletter, I receive the following error:

Mailjet::ApiError: error 400 while sending #<RestClient::Resource:0x007fa56de90e48 @url="https://api.mailjet.com/v3/REST/newsletter/7755/send", @block=nil, @options={:public_operations=>[:post], :read_only=>nil, :user=>"HASHOFUSER", :password=>"HASHOFPASSWORD", :content_type=>"application/json"}> to https://api.mailjet.com/v3/REST/newsletter/7755/send with {"Id"=>7755}

"{ \"ErrorInfo\" : \"\", \"ErrorMessage\" : \"Invalid json input: object \\\"\\\"->\\\"TNewsLetterSend\\\" property \\\"Id\\\" is not a class property, but tkInt64\", \"StatusCode\" : 400 }"

Please see http://api.mailjet.com/0.1/HelpStatus for more informations on error numbers.

from /path-to-gem/lib/mailjet/connection.rb:83:in `handle_exception'

Here is my code :

result = Mailjet::Newsletter_send.create(id: newsletter_id)

Thanks!

Resource URI have a superfluous leading slash

All resources in <mailjet_gem>/lib/mailjet/resources looks like this one :

require 'mailjet/resource'

module Mailjet
  class Contact
    include Mailjet::Resource
    self.resource_path = '/v3/REST/contact'
    self.public_operations = [:get, :put, :post]
    self.filters = [:campaign, :contacts_list, :is_unsubscribed, :last_activity_at, :recipient, :status]
    self.properties = [:created_at, :delivered_count, :email, :id, :is_opt_in_pending, :is_spam_complaining, :last_activity_at, :last_update_at, :name, :unsubscribed_at, :unsubscribed_by]   
  end
end

The first '/' in resource_path URI is useless and make RestClient generate URL with a double slash like :

RestClient.log = Logger.new(STDOUT)
Mailjet::Contact.find(1)

Prints :

RestClient.get "https://api.mailjet.com//v3/REST/contact/1", "Accept"=>"*/*; q=0.5, application/xml", "Accept-Encoding"=>"gzip, deflate"
# => 200 OK | application/json 345 bytes

The generated URL have two slashes after mailjet.com

(Bonus question, why do Accept header contains "application/xml" ?)

Cannot create a user in a contacts list

Hello,

I'm experiencing a very weird and annoying bug using the "rails_fix branch of this gem. When I run:

user = User.find 11
contact_params = {id: 1178, action: "addforce", email: user.email, first_name: user.first_name, last_name: user.last_name}
contact = Mailjet::Contactslist_managecontact.create(contact_params)

I get:

 #<Mailjet::Contactslist_managecontact:0x007fcac506ea90
 @attributes=
  {"persisted"=>false,
   "id"=>1178,
   "action"=>"addforce",
   "email"=>"[email protected]",
   "first_name"=>"First",
   "last_name"=>"Last",
   "contact_id"=>1505363094,
   "name"=>""},
 @persisted=true>

But then if I want to add another user, I get this error every time:

Mailjet::ApiError: error 400 while sending #<RestClient::Resource:0x007fcac0649348 @url="https://api.mailjet.com/v3/REST/contactslist/1178/managecontact", @block=nil, @options={:public_operations=>[:post], :read_only=>nil, :user=>"d6...", :password=>"35...", :content_type=>"application/json"}> to https://api.mailjet.com/v3/REST/contactslist/1178/managecontact with {}

"{ \"ErrorMessage\" : \"Object properties invalid\", \"StatusCode\" : 400, \"ErrorInfo\" : { \"Email\" : \"MJ08 Property email is invalid: MJ03 A non-empty value is required\", \"Action\" : \"Invalid action: \" } }"

Please see http://api.mailjet.com/0.1/HelpStatus for more informations on error numbers.

What is really weird is I quit the rails console, then it works again but only for the first try. Then the error again ...

What am I doing wrong ??

'active_support/core_ext' not required by default.

Hello,

I use mailjet (0.0.4) without rails and I got multiple issues:

  • undefined method 'in? (Same as Issue #1)
  • NoMethodError: undefined method `reverse_merge'

Everything fine when I require 'active_support/core_ext' before mailjet.

So I suppose there is a require missing somewhere.

Regards,

Create user in list

How can I create a user within a specific list ?

Is it through the Listrecipient API ? Which parameters have to be passed ?

Impossible d'inscrire quelqu'un avec la nouvelle api ?

Mailjet::Contactslist.count

Mailjet::ApiError: error 500 while sending #<RestClient::Resource:0x0000000REDACTEDa8 @url="https://api.mailjet.com//v3/REST/contactslist", @block=nil, @options={:public_operations=>[:get, :put, :post, :delete], :read_only=>nil, :user=>"REDACTED", :password=>"REDACTED"}> to https://api.mailjet.com//v3/REST/contactslist with {:limit=>1, :countrecords=>1}

"{ "ErrorIdentifier" : "REDACTED-9396-2A2101E9DBF1", "ErrorInfo" : "", "ErrorMessage" : "Unexpected database error during GET", "StatusCode" : 500 }"

Il y a un doubleslash bizarre ici :
https://api.mailjet.com//

How can I get campaign ID from newsletter

Hello,

I am trying to get campaign ID from newsletter to retrieve statistics.
But newsletter data does not include campaign ID.

How can I get campaign ID?
Am I missing something?

Thanks!

Here is my code :

create_newsletter_param = {
  Locale: "ja_JP",
  Sender: "Me",
  SenderEmail: "[email protected]",
  Subject: "test mail",
  ContactsListID: 1234,
  Title: "Test campaign"
}
newsletter = Mailjet::Newsletter.create(create_newsletter_param)
=> #<Mailjet::Newsletter:0x007f6e1cd36170
 @attributes=
  {"persisted"=>false,
   "Locale"=>"ja_JP",
   "Sender"=>"Me",
   "SenderEmail"=>"[email protected]",
   "Subject"=>"test mail",
   "ContactsListID"=>1234,
   "Title"=>"Test campaign",
   "ax_fraction"=>0,
   "ax_fraction_name"=>"",
   "callback"=>"",
   "contacts_list_id"=>1234,
   "created_at"=>Tue, 19 Apr 2016 04:46:36 +0000,
   "delivered_at"=>"",
   "edit_mode"=>"tool",
   "edit_type"=>"full",
   "footer"=>"default",
   "footer_address"=>"",
   "footer_wysiwyg_type"=>0,
   "header_filename"=>"",
   "header_link"=>"",
   "header_text"=>"",
   "header_url"=>"",
   "id"=>20045,
   "ip"=>"",
   "is_handled"=>false,
   "is_starred"=>false,
   "is_text_part_included"=>false,
   "locale"=>"ja_JP",
   "modified_at"=>"",
   "permalink"=>"default",
   "permalink_host"=>"",
   "permalink_wysiwyg_type"=>0,
   "politeness_mode"=>0,
   "sender"=>"Me",
   "sender_email"=>"[email protected]",
   "sender_name"=>"",
   "status"=>0,
   "subject"=>"test mail",
   "test_address"=>"",
   "title"=>"Test campaign",
   "url"=>""},
 @persisted=true>

Error: `undefined method `[]' for #<Set: {#<MIME::Type: application/json>}>`

I'm seeing the above error whenever I try to call any Mailjet methods from a Rails app. I can make any of the calls fine via curl or even via a plain Ruby app, but no calls at all from Rails. I'm probably doing something stupid but I can't figure it out.

Running this in curl works fine (where <api_key> and <secret_key> are the provided keys):

curl -s \
    -X POST \
    --user "<api_key>:<secret_key>" \
    https://api.mailjet.com/v3/send \
    -H "Content-Type: application/json" \
    -d '{
        "FromEmail":"[email protected]",
        "FromName":"Me",
        "Recipients": [ 
            {
            "Email":"[email protected]"
            }
        ],
        "Subject":"My first Mailjet Email!",
        "Text-part":"Greetings from Mailjet."
    }'

Running this ruby script also works fine:

require 'rubygems'
require 'mailjet'

Mailjet.configure do |config|
  config.api_key      = <api_key>
  config.secret_key   = <secret_key>
  config.default_from = '[email protected]'
end

p recipients: Mailjet::Listrecipient.all

However this, in a brand new Rails app (4.2.6) gives the error we mentioned:

# config/initializers/mailjet.rb
Mailjet.configure do |config|
  config.api_key      = <api_key>
  config.secret_key   = <secret_key>
  config.default_from = '[email protected]'
end

# in `rails console`
p recipients: Mailjet::Listrecipient.all

Full error text:

NoMethodError: undefined method `[]' for #<Set: {#<MIME::Type: application/json>}>
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/rest-client-1.6.7/lib/restclient/request.rb:307:in `type_for_extension'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/rest-client-1.6.7/lib/restclient/request.rb:312:in `type_for_extension'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/rest-client-1.6.7/lib/restclient/request.rb:286:in `block (2 levels) in stringify_headers'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/rest-client-1.6.7/lib/restclient/request.rb:286:in `map'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/rest-client-1.6.7/lib/restclient/request.rb:286:in `block in stringify_headers'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/rest-client-1.6.7/lib/restclient/request.rb:272:in `each'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/rest-client-1.6.7/lib/restclient/request.rb:272:in `inject'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/rest-client-1.6.7/lib/restclient/request.rb:272:in `stringify_headers'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/rest-client-1.6.7/lib/restclient/request.rb:92:in `make_headers'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/rest-client-1.6.7/lib/restclient/request.rb:58:in `initialize'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/rest-client-1.6.7/lib/restclient/request.rb:33:in `new'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/rest-client-1.6.7/lib/restclient/request.rb:33:in `execute'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/rest-client-1.6.7/lib/restclient/resource.rb:51:in `get'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/mailjet-1.3.8/lib/mailjet/connection.rb:65:in `handle_api_call'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/mailjet-1.3.8/lib/mailjet/connection.rb:43:in `get'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/mailjet-1.3.8/lib/mailjet/resource.rb:58:in `all'
... 11 levels...
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `load'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `block in load'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `load'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/spring-1.6.4/lib/spring/commands/rails.rb:6:in `call'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/spring-1.6.4/lib/spring/command_wrapper.rb:38:in `call'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/spring-1.6.4/lib/spring/application.rb:185:in `block in serve'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/spring-1.6.4/lib/spring/application.rb:156:in `fork'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/spring-1.6.4/lib/spring/application.rb:156:in `serve'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/spring-1.6.4/lib/spring/application.rb:131:in `block in run'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/spring-1.6.4/lib/spring/application.rb:125:in `loop'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/spring-1.6.4/lib/spring/application.rb:125:in `run'
    from /Users/alan/.rvm/gems/ruby-2.3.0@mail_spike/gems/spring-1.6.4/lib/spring/application/boot.rb:18:in `<top (required)>'
    from /Users/alan/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /Users/alan/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'

Is there something that we're missing? You can view the sample Rails app at https://github.com/urfolomeus/mail_spike

undefined method 'settings'

I'm using mailjet_api with ActionMailer and on my staging server and I get:

Completed 500 Internal Service Error in 840ms (ActiveRecord: 5.7ms)
NoMethodError (undefined method 'settings' for #<Mailjet::APIMailer:0x00000006b62398>):
app/controllers/mailer_tests_controller.rb:3 in `app_submission`

I can create an email in the rails console using the Send API no problem, but getting the above problem when I use ActionMailer.

Any direction someone can point me?

Mailjet::Resource find method can never return nil

EDIT : This issue is related to #26 . To workaround it, I forked the code and changed it to add the header "Accept-Encoding: identity" so that GZip/ZLib is not used to decode responses.

The actual code of the Mailjet::Resource#find method is :

      def find(id)
        attributes = parse_api_json(connection[id].get(default_headers)).first
        instanciate_from_api(attributes)
      rescue RestClient::ResourceNotFound
        nil
      end

So, if the resource is not found and the server returns 404, the RestClient::ResourceNotFound is raised, catched here and nil is returned.

But... connection[id].get calls handle_api_call that catches ALL RestClient exceptions and turn them into... Mailjet::ApiError in the handle_exception method so RestClient::ResourceNotFound never reaches the find method.

exception handling failure when content_type is set to json

in Mailjet::Connection#handle_api_call
when exception occur and

additional_headers[:content_type]
=> :json

json parsed payload is passed to Mailjet::Connection#handle_exception which expect it as hash, not json string.

This result in

TypeError: can't convert String into Hash
from /lib/mailjet/connection.rb:74:in `merge'

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.