GithubHelp home page GithubHelp logo

mailgun-ruby's Introduction

Mailgun-Ruby

Build Status Gem Version

This is the Mailgun Ruby Library. This library contains methods for easily interacting with the Mailgun API. Below are examples to get you started. For additional examples, please see our official documentation at https://documentation.mailgun.com

Installation

Via RubyGems

gem install mailgun-ruby

Gemfile:

gem 'mailgun-ruby', '~>1.2.14'

Usage

Here's how to send a message using the library:

require 'mailgun-ruby'

# First, instantiate the Mailgun Client with your API key
mg_client = Mailgun::Client.new 'your-api-key'

# Define your message parameters
message_params =  { from: 'bob@sending_domain.com',
                    to:   '[email protected]',
                    subject: 'The Ruby SDK is awesome!',
                    text:    'It is really easy to send a message!'
                  }

# Send your message through the client
mg_client.send_message 'sending_domain.com', message_params

Or obtain the last couple log items:

# First, instantiate the Mailgun Client with your API key
mg_client = Mailgun::Client.new 'your-secret-api-key'

# Define the domain you wish to query
domain = 'example.com'

# Issue the get request
result = mg_client.get("#{domain}/events", {:event => 'delivered'})

If you're using the EU domains, make sure you specify it when creating the client:

mg_client = Mailgun::Client.new 'your-api-key', 'api.eu.mailgun.net'

Rails

The library can be initialized with a Rails initializer containing similar:

Mailgun.configure do |config|
  config.api_key = 'your-secret-api-key'
end

Or have the initializer read your environment setting if you prefer.

To use as the ActionMailer delivery method, add this to your config/environments/whatever.rb and replace api-myapikey and mydomain.com with your secret API key and domain, respectively:

  config.action_mailer.delivery_method = :mailgun
  config.action_mailer.mailgun_settings = {
    api_key: 'api-myapikey',
    domain: 'mydomain.com',
    # api_host: 'api.eu.mailgun.net'  # Uncomment this line for EU region domains
    # timeout: 20 # Default depends on rest-client, whose default is 60s. Added in 1.2.3.
  }

To specify Mailgun options such as campaign or tags:

class UserMailer < ApplicationMailer
  def welcome_email
    mail(to: params[:to], subject: "Welcome!").tap do |message|
      message.mailgun_options = {
        "tag" => ["abtest-option-a", "beta-user"],
        "tracking-opens" => true,
        "tracking-clicks" => "htmlonly"
      }
    end
  end
end

To get the Mailgun message_id after ActionMailer has successfully delivered the email:

  mailer = UserNotifier.welcome_email(current_user)
  mailer_response = mailer.deliver_now
  mailgun_message_id = mailer_response.message_id

Response

The results are returned in a Response class:

result = mg_client.get("#{domain}/events", {:event => 'delivered'})

# To Ruby standard Hash.
result.to_h

# To YAML.
result.to_yaml

# Or raw JSON
result.body

Here's an example, breaking out the response:

mg_client = Mailgun::Client.new("your-api-key")

message_params =  {
                   from: '[email protected]',
                   to:   '[email protected]',
                   subject: 'The Ruby SDK is awesome!',
                   text:    'It is really easy to send a message!'
                  }

result = mg_client.send_message('example.com', message_params).to_h!

message_id = result['id']
message = result['message']

Debugging

Debugging the Ruby Library can be really helpful when things aren't working quite right. To debug the library, here are some suggestions:

Set the endpoint to Mailgun's Postbin. A Postbin is a web service that allows you to post data, which is then displayed through a browser. This allows you to quickly determine what is actually being transmitted to Mailgun's API.

Step 1 - Create a new Postbin. Go to http://bin.mailgun.net. The Postbin will generate a special URL. Save that URL.

Step 2 - Instantiate the Mailgun client using Postbin.

Tip: The bin id will be the URL part after bin.mailgun.net. It will be random generated letters and numbers. For example, the bin id in this URL, http://bin.mailgun.net/aecf68de, is "aecf68de".

# First, instantiate the Mailgun Client with your API key
mg_client = Mailgun::Client.new("your-api-key", "bin.mailgun.net", "aecf68de", ssl = false)

# Define your message parameters
message_params = {  from: 'bob@sending_domain.com',
                    to: '[email protected]',
                    subject: 'The Ruby SDK is awesome!',
                    text: 'It is really easy to send a message!'
                  }

# Send your message through the client
mg_client.send_message("sending_domain.com", message_params)

For usage examples on each API endpoint, head over to our official documentation pages. Or the Snippets file.

This SDK includes the following components:

Message Builder allows you to quickly create the array of parameters, required to send a message, by calling a methods for each parameter. Batch Message is an extension of Message Builder, and allows you to easily send a batch message job within a few seconds. The complexity of batch messaging is eliminated!

Testing mail deliveries

# First, instantiate the Mailgun Client with your API key
mg_client = Mailgun::Client.new 'your-api-key'

# Put the client in test mode
mg_client.enable_test_mode!

# Define your message parameters
message_params = {  from: 'bob@sending_domain.com',
                    to: '[email protected]',
                    subject: 'The Ruby SDK is awesome!',
                    text: 'It is really easy to send a message!'
                  }

# Send your message through the client
# Note: This will not actually hit the API, and will return a generic OK response.
mg_client.send_message('sending_domain.com', message_params)

# You can now access a copy of message_params
Mailgun::Client.deliveries.first[:from] # => 'bob@sending_domain.com'

Testing

There are unit tests and integration tests. Unit tests do not require Mailgun account keys. Integration tests do. By default:

bundle exec rake spec

will run just unit tests. To run integration tests:

bundle exec rake spec:integration

will run just integration tests.

bundle exec rake spec:all

will run all both types.

Integrations tests will run against VCR cassettes if they exist. If you'd like to run tests against your mailgun account, remove the cassettes.

To set up Mailgun key information. See the example file: .ruby-env.yml.example. Rename this file to .ruby-env.yml and replace the items between the <> (including the <>) with the private and public keys, and sandbox domain. Alternatively use a different domain registered in Mailgun if you have one you want to test against.

The MAILGUN_* variables in .ruby-env.yml(.example) can also be set as environment variables, if you'd like to do that instead.

Support and Feedback

Be sure to visit the Mailgun official documentation website for additional information about our API.

If you find a bug, please submit the issue in Github directly. Mailgun-Ruby Issues

As always, if you need additional assistance, drop us a note through your Control Panel at https://mailgun.com/cp/support.

mailgun-ruby's People

Contributors

0xadriatorralba avatar cycorld avatar dont-ol avatar fursich avatar iffyuva avatar jaredlt avatar leonelgalan avatar linuus avatar manuelmeurer avatar mccarths avatar mechanicles avatar mgrishko avatar mide avatar mosinski avatar n-rodriguez avatar nicolasmlv avatar nneal avatar pirogoeth avatar porbas avatar r7kamura avatar retttro avatar rzane avatar sami-b avatar shaunakpp avatar stevenwilkin avatar timdorr avatar travelton avatar velichkostoev avatar yusukehidaka avatar zainonrails 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  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

mailgun-ruby's Issues

Webhook create method returning false negative

Hey guys/gals

Really enjoying the updated library! Thanks for your time building it :)

Found a small (potential) bug. I'm calling create on the webhook client and it's working (verified the webhook is created) however it's returning false without throwing any exception.

If I get time I'll look into it and submit a PR, but for now just thought I'd raise it :)

Thanks!

Aron

Sending raw MIME does not work

When specifying the :message parameter it should write the string passed in this parameter to a file then submit that temp file to the messages.mime endpoint.

def send_message(working_domain, data)
case data
when Hash
if data.has_key?(:message)
if data[:message].is_a?(String)
data[:message] = convert_string_to_file(data[:message])
end
post("#{working_domain}/messages.mime", data)
else
post("#{working_domain}/messages", data)
end
when MessageBuilder
post("#{working_domain}/messages", data.message)
else
raise ParameterError.new("Unknown data type for data parameter.", data)
end
end

Most of this works correctly, however no matter what you pass in the :message parameter it is not converted to the file correctly, the file is always empty.

This can be replicated using the custom MIME example found on:

https://github.com/mailgun/mailgun-ruby/blob/1cb8b87a68a2d82db544bde7af388a61e3e70059/Snippets.md

undefined method 'mailgun_settings=' for ActionMailer::Base:Class

I'm consistently getting this error on server startup in an otherwise empty rails project with the following configuration:

ruby 2.3.4
rails 5.2.1
mailgun-ruby 1.1.6

development.rb

config.action_mailer.delivery_method = :mailgun
config.action_mailer.mailgun_settings = {
  api_key: "api key here",
  domain: "mailgun domain here"
}

error message

~/.rvm/gems/ruby-2.3.4/gems/actionmailer-5.1.1/lib/action_mailer/base.rb:580:in `method_missing': undefined method `mailgun_settings=' for ActionMailer::Base:Class (NoMethodError)
Did you mean?  sendmail_settings

I'm using config.action_mailer.mailgun_settings= as described in the gem's documentation. Not sure if this is a bug or a configuration issue.

should be able to send nil like every other ruby library

mail_params = {:to => params[:to],:bcc => params[:bcc],:from => params[:from],:text=> params['body'],:subject => params['subject']}
MAILGUN.send_message(domain,mail_params)

if params[:bcc] is nil, the message wont send, the errror being:
Mailgun::CommunicationError: 400 Bad Request

in ruby, sending nil usually means ignore/skip.

mailgun-ruby-1.1.3.gem does not match published SHA

The mailgun-ruby-1.1.3.gem on rubygems.org is published with a SHA that does not match the SHA of the file. This could potentially indicate that the contents of the gem have been manipulated in some way.

Bundler cannot continue installing mailgun-ruby (1.1.3).
The checksum for the downloaded `mailgun-ruby-1.1.3.gem` does not match the checksum given by the server. This means the contents of
the downloaded gem is different from what was uploaded to the server, and could be a potential security issue.

To resolve this issue:
1. delete the downloaded gem located at:
`/Users/mwp/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/mailgun-ruby-1.1.3/mailgun-ruby-1.1.3.gem`
2. run `bundle install`

If you wish to continue installing the downloaded gem, and are certain it does not pose a security issue despite the mismatching
checksum, do the following:
1. run `bundle config disable.checksum_validation true` to turn off checksum verification
2. run `bundle install`

(More info: The expected SHA256 checksum was "2542b467788ab91479a84617f9aeeb02c1446a52229d80d0a857bed20839d80c", but the checksum
for the downloaded gem was "da81bdb633549e3035252fe1d89f967396bff93d1a7b194c7ba424cbb906c2ad".)

Snippets.md contains incorrect syntax for MessageBuilder

Running the following lines will cause an error:

mb_obj.set_from_address :from, "[email protected]", {'first' => 'Sending', 'last' => 'User'}
mb_obj.add_recipient :to, "[email protected]", {'first' => 'Recipient', 'last' => 'User'}
mb_obj.set_subject :subject, "This is the subject!"
mb_obj.set_text_body :text, "This is the text body."

That's because set_from_address should not contain a :from argument. Same goes for :subject and :text, and for the subsequent BatchMessage lines.

PR to follow.

Better documentation wanted

How would one go about using a txt.erb template file for building up a message dynamically?
Attachments in the message_params hash?

Why not a proper list or readme for all these things? Most certainly the basics. Now the only thing online that adds some clarification is a message on mailgun's blog from 2014 and a very short readme?!
I got stuff working somewhat, but I thought the goal of an API should be to make things simpler.

Better Exceptions

I appreciate the pastebin-esque method of debugging emails, but it's cumbersome and doesn't help debug with the exact error you have.

Why not have custom exceptions that the library understands and get thrown with the approriate HTTP response?

400 is used as a blanket error - can we at least parse the HTTP error messages from the API and throw a more helpful exception?

Mailgun::Api::InvalidRequest message="Please specify a message body with your request"

The actual exception format needs to be thought through, but this would be a huge improvement over the pastebin.

Trouble with "count" parameter

I am trying to get counts of certain events.

I am using the following

client.get("mg.mydomain.com/events", { count: 'true', event: 'clicked' }) 

However, I'm getting the error:

Mailgun::CommunicationError: {
  "message": "Unknown parameter: count=['yes']"
}

I tried a few other variations, but could not get anything to work. I am referencing the docs here: http://documentation.mailgun.com/api-campaigns.html#events which I believe should allow for the count param that I'm using. If I remove "count", the request will go through, but I get the actual events rather than the count. I want the counts to do some stats on my end.

Thank you!

Neal

(slightly dumb question) Why adapters?

Hello,
I am configuring my app to work with MailGun, which is awesome.
Without even thinking, I quickly googled for a mailgun gem, quickly installed it and everything worked straight away. I could send confirmation emails and receive them in my inbox.

I then tried without a gem (or adapter) and it worked pretty much the same way (the email went straight to the trash, actually. Not sure why) so I am wondering. Why the need for an adapter? Should I re-install the adapter gem and do it that way instead?

My code literally changed from:


  config.action_mailer.delivery_method = :mailgun

  config.action_mailer.smtp_settings = {
    :api_key           => ENV['MAILGUN_API_KEY'],
    :domain           => ENV['MAILGUN_DOMAIN']
  }

to: (without the extra gem dependency!)


  config.action_mailer.delivery_method = :smtp

  config.action_mailer.smtp_settings = {
    :port           => ENV['MAILGUN_SMTP_PORT'],
    :address        => ENV['MAILGUN_SMTP_SERVER'],
    :user_name      => ENV['MAILGUN_SMTP_LOGIN'],
    :password       => ENV['MAILGUN_SMTP_PASSWORD'],
    :domain         => ENV['MAILGUN_DOMAIN'],
    :authentication => :plain,
  }

Batch sending adds everyone to the To field

The bug

When you batch send a message with the mailgun-ruby gem, using the Mailgun::BatchMessage class, every recipient sees themselves and all the other recipients in the To field.

How to reproduce

I used this code. I'm using rails, so Action Mailer is responsible for rendering the message:

mail = FooMailer.a_batch_email(recipients)

client = Mailgun::Client.new(ENV["MAILGUN_API_KEY"])
batch_message = Mailgun::BatchMessage.new(client, "mail.community.hackerschool.com")

batch_message.set_from_address(mail.from.first)
batch_message.set_subject(mail.subject)
batch_message.set_text_body(mail.body.to_s)

mail.to.each do |recipient|
  batch_message.add_recipient(:to, recipient)
end

batch_message.finalize

The only difference from https://github.com/mailgun/mailgun-ruby/blob/master/Messages.md is that I'm not passing in any recipient variables, but this should be fine because BatchMessage#add_recipient creates default recipient variables if nothing is passed as a third argument.

What I expect

Each recipient in mail.to should receive a copy of the email with only their email address in the To field.

What actually happens.

Each recipient in mail.to receives an email with everyone in mail.to in the To field.

Using the API directly by following the instructions in the docs works as expected.

Mailgun::BatchMessage doesnt replace the placeholders with recipient data.

The Mailgun::BatchMessage doesn't replace the placeholders in the email.

I'm trying to construct the batch message from a csv file
It works with "%recipient.account_id%" but not with "%account_id%", even thought the documentation states that it should

batch = Mailgun::BatchMessage.new(Mailgun::Client.new, Mailgun.domain)
# pretend that from and subject are set
batch.body_html("<p>%account_id%</p>")

csv_data.each do |d|
  batch.add_recipient(:to, d[:email], d.to_h)   
end

puts batch.recipient_variables
batch.finalize

Csv data example:

d = {
  email: "[email protected]",
  account_id: 123
}

The recipient_variables puts out correct info, however i can't seem to find it in the log and the "%account_id%" doesn't get replaced

{
   "[email protected]" => {
      email:  "[email protected]",
      account_id: 123
  }
}

Looks like the same as in #22

Relevant documentation:
http://blog.mailgun.com/the-official-mailgun-ruby-sdk-is-here/
https://github.com/mailgun/mailgun-ruby/blob/master/docs/Messages.md#usage---batch-message

Problem with generate_hash Method in OptInHandler

Hi there,

i'm using the Opt-In Handler Method for the mailgun gem. My problem is, that the generated hash is too long, so i have problems to call the url in a mail from a web mail portal like www.web.de. Is there a possibility to manipulate the hash for the Opt In Validation ?

Best regards,
Christian

Custom headers

I'm using the mailgun-ruby gem to send messages through ActionMailer. I'm trying to attach custom headers so I can identify these messages in my web hooks, but the headers don't seem to go through. (When I check the mailgun logs, they aren't there, and they also aren't transmitted in the web hooks.) Here is an example of my method. Any ideas?

  def invitation(invitation_id, reminder=false)
    @invitation = ProviderInvitation.find(invitation_id)
    headers 'X-Mailgun-Variables' => {provider_invitation_id: invitation_id.to_s, mail_type: "provider_invitation"}.to_json
    if reminder
      mail(to: @invitation.invited_email, from: "Contact <[email protected]>", subject: "Reminder: #{@invitation.sending_provider.name} invited you to join!")
      @invitation.update(reminder_sent: true)
    else
      mail(to: @invitation.invited_email, from: "Contact <[email protected]>", subject: "#{@invitation.sending_provider.name} invited you to join!")
    end
  end

Merge Fields not Working

I'm trying to send emails through the mailgun-ruby gem, and it doesn't seem to be merging the fields when sent.

I've been able to reproduce the problem with the following code:

require 'mailgun'

mailgun_client = Mailgun::Client.new("[MAILGUN KEY]")

message = Mailgun::BatchMessage.new(mailgun_client, "mail.domain.com")
message.set_from_address("[email protected]")
message.set_subject("Merge Fields Test")
message.set_text_body("Hello %recipient.first%, this is a test. Your full name is %recipient.first% %last%.")

message.add_recipient(:to, "[email protected]", {"first" => "John", "last" => "Doe"})
message.add_recipient(:to, "[email protected]", {"first" => "Jane", "last" => "Doe"})

message.finalize

Each recipient is getting the non-merged emails with all recipients in the "to" address.

Error handling if queue is full

Right now if the mailgun queue is full (500k emails) you will get an error back.
Error handling should cover this, by either retrying after waiting some seconds or issue an error that says "you may retry in a couple of seconds".
This may even happen on a single email (without batch).

When you use the API for ActionMailer this is even worse as emails are just not sent.

Mailgun::Suppressions

Is there any reason 'mailgun/suppressions' is not loaded? I noticed there's also no docs for it but the code exists and works if I require it in myself.

POST to "lists" returns 400 Bad Request

result = @mg_obj.post("lists", {:address => @ml_address,
:name => 'Integration Test List',
:description => 'This list should be deleted automatically.',
:access_level => 'members'})

While trying to make a POST to lists, I receive a 400 Bad Request error. I have tried running the above code straight from your spec and it fails as well. I have other code that is making successful POST requests using the same API key as what is being used to create a list.

rest-client version conflicts

Can we lower the rest-client dependency, as it's conflicting with other gems:

In snapshot (Gemfile.lock):
   rest-client (= 1.8.0)

 In Gemfile:
   lob was resolved to 2.5.1, which depends on
     rest-client (< 3.0, >= 1.8)

   mailgun-ruby (>= 1.1.6, ~> 1.1) was resolved to 1.1.6, which depends on
     rest-client (~> 2.0)

   stripe was resolved to 1.31.0, which depends on
     rest-client (~> 1.4)

   stripe was resolved to 1.31.0, which depends on
     rest-client (~> 1.4)

Can't install mailgun gem

C:\Users\lectricas\Documents\obed18-menu>bundle install
Fetching gem metadata from https://rubygems.org/
Fetching version metadata from https://rubygems.org/
Could not find gem 'mailgun-ruby (~> 1.0.5) x64-mingw32' in any of the gem
sources listed in your Gemfile or available on this machine.

C:\Users\lectricas\Documents\obed18-menu>]

Including 'mailgun-ruby' causes action_mailer configs in an initializer to not be used

Hello, I have encountered an odd scenario where I am unable to set action_mailer configuration options if I include the mailgun-ruby gem.

I have a Rails 4.2.7.1 app, where I configure ActionMailer in an initializer. Some of the options I set are the default_url_options and asset_host, so that images in our emails have an absolute URL rather than a relative one. Without requiring mailgun-ruby, emails are generated correctly. As soon as I add gem 'mailgun-ruby' to my Gemfile, these options are no longer present at the time the email is rendered. This causes an exception to be throw by Rails stating that the default_url_options are not set.

I did some digging, and found that the root cause is the Railgun::Railtie, which adds the mailgun delivery method in before_initialize hook. I can not find any explanation either in Rails or elsewhere that would explain why adding a delivery method would cause subsequent configuration to not be used. I looked at the Rails initialization events and found nothing that points to a reason why.

I am able to work around this issue by requiring all necessary files except the Railtie. I'm not actually using the mailgun delivery method, my use case requires me to manually call Railgun.transform_for_mailgun(mail) and client.send_message('my-domain', message_payload), so adding the following to my Gemfile works:

gem 'mailgun-ruby', '~>1.1.4', require: ['mailgun', 'railgun/attachment', 'railgun/errors', 'railgun/mailer', 'railgun/message']

Do you have any thoughts on why this might be happening?

For development, my initializer is effectively this:

# config/initializers/action_mailer.rb
Rails.application.config.action_mailer.default_url_options = { host: 'localhost', :port: 3000, protocol: 'http' }
Rails.application.config.action_mailer.asset_host = 'http://localhost:3000'
Rails.application.config.action_mailer.delivery_method = :smtp
Rails.application.config.action_mailer.smtp_settings = {
  address: 'smtp.mailgun.org',
  port: 587,
  domain: 'my-domain',
  user_name: 'username',
  password: 'supersecret',
  authentication: 'plain',
  enable_starttls_auto: true,
}
Rails.application.config.action_mailer.perform_deliveries = false

digest/hmac removed in ruby 2.2.0-preview1

so, im running into this issue:

vendor/ruby/2.2.0/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `require': cannot load such file -- digest/hmac (LoadError)
from vendor/ruby/2.2.0/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `block in require'
from vendor/ruby/2.2.0/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:214:in `load_dependency'
from vendor/ruby/2.2.0/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `require'
from vendor/ruby/2.2.0/gems/mailgun-ruby-1.0.2/lib/mailgun/lists/opt_in_handler.rb:4:in `<top (required)>'
from vendor/ruby/2.2.0/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `require'
from vendor/ruby/2.2.0/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `block in require'
from vendor/ruby/2.2.0/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:214:in `load_dependency'
from vendor/ruby/2.2.0/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `require'
from vendor/ruby/2.2.0/gems/mailgun-ruby-1.0.2/lib/mailgun.rb:7:in `<top (required)>'
from vendor/ruby/2.2.0/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `require'
from vendor/ruby/2.2.0/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `block in require'
from vendor/ruby/2.2.0/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:214:in `load_dependency'
from vendor/ruby/2.2.0/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `require'
from vendor/ruby/2.2.0/gems/rails-mailgun-0.2.0/lib/rails-mailgun.rb:3

looks like digest/hmac is removed from ruby-2.2.0-preview1: ruby/ruby@24be1f1

Incorrect message_id after sending the message via rails mailer

Hi!

I have just installed the gem in one of our projects and it seems to work fine. However, I've noticed that I cannot get the Message-ID after sending the email. Following the documentation in the README:

  mailer = UserNotifier.welcome_email(current_user)
  mailer_response = mailer.deliver_now
  mailer_response.message_id => Returns the string "id" instead of the message id.

The message is sent through mailgun correctly, however the last line returns the string "id" instead of the message id (i was expecting something like [email protected].

Looking at the code, I could get the right Message-ID by changing just one line of code. Open the file lib/railgun/mailer.rb and change the deliver! function from:

    def deliver!(mail)
      mg_message = Railgun.transform_for_mailgun(mail)
      response = @mg_client.send_message(@domain, mg_message)
      if response.code == 200 then
        mg_id = response.body['id']  <<-----
        mail.message_id = mg_id
      end
      response
    end

to

    def deliver!(mail)
      mg_message = Railgun.transform_for_mailgun(mail)
      response = @mg_client.send_message(@domain, mg_message)
      if response.code == 200 then
        mg_id = response.to_h['id'] <<-----
        mail.message_id = mg_id
      end
      response
    end

and then I get the correct message id.

I'm using ruby 2.4.1 and the latest version of the gem (1.1.6). Any idea what I might be doing wrong?

Attachments are ignoring filename when sent using ActionMailer

I have Rails 5.0.1 using ActionMailer code as follows:

  def pdf_quote(proposal)
    @proposal = proposal
    email_with_name = %("#{@proposal.first_name} #{@proposal.last_name}" <#{@proposal.email}>)
    @filename = "QD-#{@proposal.qd_number}_#{@proposal.last_name}.pdf"
    attachments[@filename] = {
      mime_type: 'application/pdf',
      encoding: 'Base64',
      content: @proposal.pdf_base64
    }  
    mail(
      to: email_with_name,
      from: 'Floorbook UK <email address>',
      subject: 'Your Personal Flooring Quote is attached',
      sent_on: Time.now
      )    
  end

I have tried by hardcoding 'test.pdf' also. I have tried replace flilename: with remoteName inside the hash (as I see th PHP plugin uses remoteName).

No matter what I try the filename does not appear in the JSON in the mailgun logs.

I can however see it in the Rails log. For example, here is the log when I tried using remotename:

----==_mimepart_58acb0bbc5906_b35a3ff9c303fa14374b
Content-Type: application/pdf
Content-Transfer-Encoding: quoted-printable
Content-Disposition: attachment;
 filename=QD-1002_McSharry.pdf
remotename: QD-1002_McSharry.pdf
Content-ID: <58acb0bbc8aaf_b35a3ff9c303fa14376d9@Richards-MacBook-Air.local.mail>

%PDF-1.3

Here is the relevant part of the JSON from the mailgun log:

"message": {
"headers": {
"to": "Richard McSharry ",
"message-id": "20170221213251.124698.55612.AAE859F0@sandbox4d05645e78ac4c81b7b542d27c5e87ad.mailgun.org",
"from": "Floorbook UK ",
"subject": "Your Personal Flooring Quote is attached"
},
"attachments": [
{
"filename": "",
"content-type": "application/pdf",
"size": 9004
}
],
"recipients": [
"my email"
],
"size": 11517
},

Implement Railgun as a Railtie

Thanks for adding the railgun stuff in the last version! Makes my life a lot easier.

One thing I missed initially was the need to include a require 'railgun' at the top of my production.rb. That's because the railgun stuff doesn't autoload, which makes sense in the case of a non-Rails project.

You could simply add a require 'railgun' if defined?(Rails) to your mailgun-ruby.rb file and call it a day. But what would be more semantic for Rails would be to implement a Railtie. For now, it would be to simply move this line out of the global context and into an initializer method instead. But there could be other things that could be added down the line.

I'm more than happy to work up a PR. Just wanted to write this down as an issue first before I forget ๐Ÿ˜„

Passing nil/empty bcc parameter is transformed to array with blank string

I've integrated the client into my rails project and in some of my mailers I've a dynamic list of people to bcc and sometimes that ends up being no one. However whenever a nil/empty value is passed in for the bcc field the mailer bombs out.

How to reproduce the error.

mg_client = Mailgun::Client.new("your-api-key")
mail = Mail::Message.new(to: '[email protected]', cc: ['[email protected]'], bcc: []) # bcc: nil/'' also fails
mg_message = Railgun.transform_for_mailgun(mail)
mg_client.send_message('mg.domain.com', mg_message)

Results in the error below since it has bcc as bcc: [""]
Mailgun::CommunicationError: 400 Bad Request: 'bcc' parameter is not a valid address. please check documentation

prevent sending multi-part mail if only html or text part is provided

When a rails app sends only a text mail, then Railgun sends also the html part (converted from the text part).

The problem, is that all newlines are ignored, when the mail is view in an html capable mail client.

e.g. if the text part of a mail has two lines

first line
second line

then it will be shown as one line in a mail-client with html support.:

first line second line

this code is the cause of the problem

Might be wise to mark this as abandoned

Given that this hasn't been updated in a year, isn't updated to the v3 API, and the maintainers aren't replying to PRs or issues, I think it would be wise to not give users the idea that this is being maintained.

Please correct me if this is being maintained in some capacity.

`set_delivery_time': wrong number of arguments (2 for 1)

The docs (MessageBuilder.md and Messages.md) say you're supposed to use this syntax: mb_obj.set_delivery_time("tomorrow 8:00AM", "PST");

But the actual def in message_builder.rb only includes one parameter: def set_delivery_time(timestamp) and the unit test only tests for one parameter as well.

(I'd issue a pull request, but I'm not familiar enough with Ruby to contribute confidently.)

Wrong communication error handling

From time to time there is connection error to mailgun service which is not properly handled.

undefined method `response' for #<Errno::ECONNREFUSED: Connection refused - connect(2)>
../shared/bundle/ruby/gems/mailgun-ruby-1.0.2/lib/mailgun.rb:94:in `rescue in get'
../shared/bundle/ruby/gems/mailgun-ruby-1.0.2/lib/mailgun.rb:86:in `get'
../shared/bundle/ruby/gems/mailgun-ruby-1.0.2/lib/mailgun/events/events.rb:50:in `_get'
../shared/bundle/ruby/gems/mailgun-ruby-1.0.2/lib/mailgun/events/events.rb:28:in `get'

I'll try to provide pull request soon

Reply to does not work using message builder

message_builder = Mailgun::MessageBuilder.new
message_builder.add_recipient('h:reply-to', '[email protected]')

should set the reply to. That doesn't work, nor does:
message_builder.add_custom_parameter('h:reply-to', '[email protected]')
The issue here, is if an array of reply-to addresses is posted, then the reply to address does not get set (or at least does not seem to be in gmail).
I'd suggest that either:
(1) Complex_setter and simple_setter should not create arrays of size one.
(2) The MailGun backend that receives these parameters should treat these the same.

Presently there is no good way to set the reply to address. I've resorted to using:
message_builder.message['h:Reply-To'] = '[email protected]' which feels like a bit of hack.

I would create a PR for (1) if you like.

Test mode?

Hey there! Really loving the new Mailgun gem - thanks for the good work.

One thing that I'm running into in my testing is that it's annoying to stub Mailgun out every time I hit an action in my app that sends an email. It would be awesome to be able to do something like

Mailgun.enable_test_mode!

in my spec_helper.rb that would then cause all the client to not actually make requests to Mailgun.

I was thinking about working on this and opening a pull request, but wanted to see your folks' thoughts on it in case you have other suggestions or a better approach before I go down that path.

Thanks!

Ruby 2.0.0-0p end of life

Hey mailgun team.

The .ruby-version is currently on 2.0.0-0p which is considered end of life. Any plans to bring this up to a more update to date version? Happy to work on it if you'd like.

Cheers,

Aron

Unexpected token at 'Mailgun Magnificent API'

I'm trying to send emails in background using delayed_job but for some reason raises Unexpected token at 'Mailgun Magnificent API' error. This only happens in production environment...

Invalid delivery method

I am getting this error after commenting out config.action_mailer.mailgun_settings as it was raising undefined method mailgun_settings=' for ActionMailer::Base:Class`

Configuration:

  • Rails 4.2.8
  • Ruby 2.4.1
  • mailgun-ruby 1.1.6
  • Error Message is Invalid delivery method mailgin

Mailgun::Error (Too many recipients, max is 1000):

Hello;

i'm completely stuck with the following error Mailgun::Error (Too many recipients, max is 1000)

I'm using the following piece of code to deliver email in batch :

recipients.in_groups_of(500) do |group|
hash = {}
group.compact.each do |r|
  hash["#{r["email"]}"] = {name: "#{r["firstname"]}", id: r.id }
end
to = recipients.collect{ |r| r.email }.join(",")
parameters[:to] = to
parameters[:'recipient-variables'] = hash.to_json
Mailgun().messages.send_email(parameters)
end

(i might be missing some pieces but it was working before correctly โ€” before we reached 1000 total recipients). Parameters contains an array of email adresses, which has been limited to 500. I don't get why I till get this error

Thanks if anyone has clues about it

Best regards

Impossible to install gem because of missing dependency 'multimap'

I am trying to install the gem on Mac and Ubuntu but without success. Multimap is yanked on rubygems.org.

โžœ  test_howitzer_framework  gem install mailgun-ruby                                        ruby-2.0.0-p353@test_howitzer_framework
ERROR:  While executing gem ... (Gem::UnsatisfiableDependencyError)
    Unable to resolve dependency: 'mailgun-ruby (= 1.0.0)' requires 'multimap (~> 1.1)'

Error informativeness is abysmal

Could you please make errors more informative?

On multiple occasions (with different reasons), I got:

Mailgun::CommunicationError: undefined method `each_byte' for nil:NilClass
    from /Users/zzz/.rvm/gems/ruby-2.2.3/bundler/gems/mailgun-ruby-cae112741ae8/lib/mailgun/client.rb:58:in `rescue in post'
    from /Users/zzz/.rvm/gems/ruby-2.2.3/bundler/gems/mailgun-ruby-cae112741ae8/lib/mailgun/client.rb:55:in `post'
    from /Users/zzz/.rvm/gems/ruby-2.2.3/bundler/gems/mailgun-ruby-cae112741ae8/lib/mailgun/client.rb:39:in `send_message'

This communication error is absolutely uninformative and there is nothing I can do with it except prying deep inside rest-client for possible clues.

Error installing gem

I get this, when I trying to install through gem install

Fetching: json-1.8.2.gem (100%)
Building native extensions.  This could take a while...
ERROR:  Error installing mailgun-ruby:
ERROR: Failed to build gem native extension.

    /usr/bin/ruby1.9.1 extconf.rb
/usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- mkmf         (LoadError)
    from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from extconf.rb:1:in `<main>'


Gem files will remain installed in /var/lib/gems/1.9.1/gems/json-1.8.2 for inspection.

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.