Giter VIP home page Giter VIP logo

mailgun's Introduction

Mailgun rubygem

This gem allows for idiomatic Mailgun usage from within ruby. Mailgun is a kickass email-as-a-service that lets you use email as if it made sense. Check it out at http://mailgun.net

Mailgun exposes the following resources:

  • Sending email
  • Mailing Lists
  • Mailing List Members
  • Mailboxes
  • Routes
  • Log
  • Stats
  • Messages
  • Bounces
  • Unsubscribes
  • Complaints
  • Domain management
  • Webhook management
  • Address Validation

Patches are welcome (and easy!).

Sending mail using ActionMailer

If you simply want to send mail using Mailgun, just set the smtp settings in the Rails application like the following. Replace wherever necessary in the following snippet :)

ActionMailer::Base.smtp_settings = {
  :port           => 587,
  :address        => 'smtp.mailgun.org',
  :user_name      => '[email protected]',
  :password       => 'mailgun-smtp-password',
  :domain         => 'your.mailgun.domain',
  :authentication => :plain,
}
ActionMailer::Base.delivery_method = :smtp

Usage

We mimic the ActiveRecord-style interface.

Configuration

# Initialize your Mailgun object:
Mailgun.configure do |config|
  config.api_key = 'your-api-key'
  config.domain  = 'your-mailgun-domain'
end

@mailgun = Mailgun()

# or alternatively:
@mailgun = Mailgun(:api_key => 'your-api-key')

Sending Email

parameters = {
  :to => "[email protected]",
  :subject => "missing tps reports",
  :text => "yeah, we're gonna need you to come in on friday...yeah.",
  :from => "[email protected]"
}
@mailgun.messages.send_email(parameters)

Mailing Lists

# Create a mailing list
@mailgun.lists.create "[email protected]"

# List all Mailing lists
@mailgun.lists.list

# Find a mailing list
@mailgun.lists.find "[email protected]"

# Update a mailing list
@mailgun.lists.update("[email protected]", "[email protected]", "Developers", "Develepor Mailing List")

# Delete a mailing list
@mailgun.lists.delete("[email protected]")

Mailing List Members

# List all members within a mailing list
@mailgun.list_members.list "[email protected]"

# Find a particular member in a list
@mailgun.list_members.find "[email protected]", "[email protected]"

# Add a member to a list
@mailgun.list_members.add "[email protected]", "[email protected]"

# Add multiple mailing list members to a list (limit 1,000 per call)
@mailgun.list_members.add_multi "[email protected]", [{"address": "Alice <[email protected]>", "vars": {"age": 26}}, {"name": "Bob", "address": "[email protected]", "vars": {"age": 34}}].to_json, {:upsert => true}
    
# Update a member on a list
@mailgun.list_members.update "[email protected]", "[email protected]", "Q", {:gender => 'male'}.to_json, :subscribed => 'no')

# Remove a member from a list
@mailgun.list_members.remove "[email protected]", "[email protected]"

Mailboxes

# Create a mailbox
@mailgun.mailboxes.create "[email protected]", "password"

# List all mailboxes that belong to a domain
@mailgun.mailboxes.list "domain.com"

# Destroy a mailbox (queue bond-villian laughter)
# "I'm sorry Bond, it seems your mailbox will be... destroyed!"
@mailbox.mailboxes.destroy "[email protected]"

Bounces

# List last bounces (100 limit)
@mailgun.bounces.list

# Find bounces
@mailgun.bounces.find "[email protected]"

# Add bounce
@maligun.bounces.add "[email protected]"

# Clean user bounces
@mailbox.bounces.destroy "[email protected]"

Routes

# Initialize your Mailgun object:
@mailgun = Mailgun(:api_key => 'your-api-key')

# Create a route
# Give it a human-readable description for later, a priority
# filters, and actions
@mailgun.routes.create "Description for the new route", 1,
     [:match_recipient, "[email protected]"],
     [[:forward, "http://my-site.com/incoming-mail-route"],
      [:stop]]

# List all routes that belong to a domain
# limit the query to 100 routes starting from 0
@mailgun.routes.list 100, 0

# Get the details of a route via its id
@mailgun.routes.find "4e97c1b2ba8a48567f007fb6"

# Update a route via its id
# (all keys are optional)
@mailgun.routes.update "4e97c1b2ba8a48567f007fb6", {
     :priority   => 2,
     :expression => [:match_header, :subject, "*.support"],
     :actions    => [[:forward, "http://new-site.com/incoming-emails"]]
     }

# Destroy a route via its id
@mailbox.routes.destroy "4e97c1b2ba8a48567f007fb6"

Supported route filters are: :match_header, :match_recipient, and :catch_all

Supported route actions are: :forward, and :stop

Domains

# Add a domain
@mailgun.domains.create "example.com"

# List all domains that belong to the account
@mailgun.domains.list

# Get info for a domain
@mailgun.domains.find "example.com"

# Remove a domain
@mailbox.domains.delete "example.com"

Webhooks

# List of currently available webhooks
@mailgun.webhooks.available_ids

# Returns a list of webhooks set for the specified domain
@mailgun.webhooks.list

# Returns details about the webhook specified
@mailgun.webhooks.find(:open)

# Creates a new webhook
# Note: Creating an Open or Click webhook will enable Open or Click tracking
@mailgun.webhooks.create(:open, "http://bin.example.com/8de4a9c4")

# Updates an existing webhook
@mailgun.webhooks.update(:open, "http://bin.example.com/8de4a9c4")

# Deletes an existing webhook
# Note: Deleting an Open or Click webhook will disable Open or Click tracking
@mailgun.webhooks.delete(:open)

Address Validation

Requires the public_api_key to be set. The Mailgun public key is available in the My Account tab of the Control Panel.

# Given an arbitrary address, validates address based off defined checks
@mailgun.addresses.validate('[email protected]')

Making Your Changes

  • Fork the project (Github has really good step-by-step directions)

  • Start a feature/bugfix branch

  • Commit and push until you are happy with your contribution

  • Make sure to add tests for it. This is important so we don't break it in a future version unintentionally.

  • After making your changes, be sure to run the Mailgun tests using the rspec spec to make sure everything works.

  • Submit your change as a Pull Request and update the GitHub issue to let us know it is ready for review.

TODO

  • Add skip and limit functionality
  • Distinguish failed in logs
  • Distinguish delivered in logs
  • Tracking?
  • Stats?
  • Campaign?

Maintainers

Authors

See CONTRIBUTORS.md file for contributor credits.

License

Released under the MIT license. See LICENSE for more details.

mailgun's People

Contributors

adamof avatar adelevie avatar ajsharp avatar alansikora avatar andresbravog avatar baphled avatar epiphanymachine avatar gabriel avatar hairihan avatar hashnuke avatar hudecv avatar kazw avatar mirzac avatar omotenko avatar scotterc avatar sgrove avatar stabenfeldt avatar zdraganov 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

mailgun's Issues

How to display received emails...

I want to display received emails. suppose we sent one document or message through our gmail address to [email protected]. i need to grep those emails to my apps. for this what i can do. please help me here i want to deliver my application ASAP.

Broken multimap gem dependency

Hello,
I tried to install mailgun 0.7 with 'bundle install' and got this error message:

Could not find gem 'multimap (>= 0) ruby', which is required by gem 'mailgun (~> 0.7) ruby', in any of the sources.

On https://rubygems.org/gems/multimap : "This gem has been yanked".

I installed gem multimap from manually downloaded but I cannot use this way with deploying on Heroku hosting.

Add multi address into maillist in one time

Hi HashNuke,

How can I adding several email addresses into one maillist in one time?
I tried to using following method, but it's only support to add one address.
It will cause timeout err when there are a plenty amount of address.

# Adds a mailing list member with a given address
    # NOTE Use create instead of add?
    def add(member_address, options={})
      params = {:address => member_address}
      Mailgun.submit :post, list_member_url, params.merge(options)
    end

Batch mail?

This is the only thing I feel like this gem is missing. Is there a way to batch send?

Parameter hash sent to RestClient not working

When I perform a Mailgun().routes.create or Mailgun().routes.update command, I get the following error:

{                                           
  "message": "'action' parameter is missing"
}                                           

I debugged the problem and found that at https://github.com/HashNuke/mailgun/blob/master/lib/mailgun/base.rb#L71 RestClient is not recognizing the parameters hash passed to it and not posting parameters to Mailgun, even though it has data.

Here's my test code:

  def self.create(pattern)                                                     
    mailgun.routes.create "Catch-all route for #{ENV['MAILGUN_ROUTE_DOMAIN']}",
      DEFAULT_PRIORITY,                                                        
      [:match_recipient, pattern],                                             
      [[:forward, endpoint_url], [:stop]]                                      
  end                                                                          

  # ...

  describe '.create' do                                         
    let(:pattern) { '.*@.*.test.com' }                      

    it 'creates a route' do                                     
      VCR.use_cassette :email_route_create do                   
        EmailRoute.create pattern                               

        expect(EmailRoute.existing_route(pattern)).to be_present
      end                                                       
    end                                                         

  end                                                           

Here's a dump of my VCR cassette during a create:

---                                                                                
http_interactions:                                                                 
- request:                                                                         
    method: post                                                                   
    uri: https://api:[email protected]/v2/routes
    body:                                                                          
      encoding: UTF-8                                                              
      string: ''                                                                   
    headers:                                                                       
      Accept:                                                                      
      - "*/*; q=0.5, application/xml"                                              
      Accept-Encoding:                                                             
      - gzip, deflate                                                              
      User-Agent:                                                                  
      - Ruby                                                                       
  response:                                                                        
    status:                                                                        
      code: 400                                                                    
      message: BAD REQUEST                                                         
    headers:                                                                       
      Server:                                                                      
      - nginx/1.4.7                                                                
      Date:                                                                        
      - Wed, 27 Aug 2014 00:50:55 GMT                                              
      Content-Type:                                                                
      - application/json                                                           
      Content-Length:                                                              
      - '48'                                                                       
      Connection:                                                                  
      - keep-alive                                                                 
    body:                                                                          
      encoding: UTF-8                                                              
      string: |-                                                                   
        {                                                                          
          "message": "'action' parameter is missing"                               
        }                                                                          
    http_version:                                                                  
  recorded_at: Wed, 27 Aug 2014 00:53:28 GMT                                       
recorded_with: VCR 2.9.2                                                           

Attaching data to messages

Hi guys - bit unsure if / how this can be used to attached custom data to messages in order to have it returned from Mailgun via webhook...

To add this header to your message:

API: Pass the following parameter, “v:my-custom-data” => “{“my_message_id”: 123}”.

Route example in README broken?

Copy-pasting the example in the README yields a Mailgun::Error:

irb(main):013:0> @mailgun.routes.create "Description for the new route", 1,
irb(main):014:0*        [:match_recipient, "[email protected]"],
irb(main):015:0*        [[:forward, "http://my-site.com/incoming-mail-route"],
irb(main):016:1*           [:stop]]
Mailgun::Error: 'action' parameter is missing

Routes list doesn't default to configured domain

Great gem! Thanks for all the effort put in. A question on usage though, if I configure a domain in an initializer I would've assumed that I wouldn't also need to specify the domain in routes list method call. ie

# Initialize your Mailgun object:
Mailgun.configure do |config|
  config.api_key = 'your-api-key'
  config.domain  = 'your-mailgun-domain'
end

@mailgun = Mailgun()
# I'd expect this line to work
@mailgun.routes.list() # but it returns 'key not found: :domain'

# Instead I need to use this
@mailgun = Mailgun(domain: Mailgun.domain)
@mailgun.routes.list() # And now this works

Thoughts?

Unable to add vars to a list member

irb>   @mailgun.list_members.update(
    '[email protected]',  
    email, "Q", 
    {:gender => 'male'}, 
    :subscribed => 'no'
)

{
     "member" => {
        "subscribed" => true,
              "name" => "Q",
              "vars" => {},
           "address" => "[email protected]'"
    },
    "message" => "Mailing list member has been updated"
}

Tried to follow the exemples in the doc, am I doing it wrong?

To receive email

Hi,

Does this gem support to receive emails to rails app ?

Thanks.

Getting members of list by vars

Hi, Is it possible to get members of list by vars?
What I have is:

@mailgun.list_members('MY_LIST').list()
=> [{"address"=>"[email protected]", "name"=>"", "subscribed"=>true, "vars"=>{}},
 ]

I'm trying to do something like this:

@mailgun.list_members('MY_LIST').list({ vars: { type: 'daily'}})
=> [,
 ]

and getting the same array.

But when I try to do like this:

@mailgun.list_members(MY_LIST).list({ address: '[email protected]'})
=> []

It gives correct response.
How can I use vars correctly?

Test Mode appears to not be working

v 0.11
Converting to test mode for my test suite. This code sends a message not in test mode

@mailgun = Mailgun(api_key: ENV['MAILGUN_API_KEY'], domain: ENV['MAILGUN_DOMAIN'], test_mode: true )
message_params = {
      from: ENV['MAILGUN_USER_NAME'],
      to: "[email protected]",
      subject: "You've been invited to join the BlueStreak Platform!",
      html: html_output.to_str
    }.merge(opts)
   @mailgun.messages.send_email(message_params)

And (part of) the mailgun logs for my request:

...
flags": {
        "is-routed": false,
        "is-authenticated": true,
        "is-system-test": false,
        "is-test-mode": false
    },
...

Note the "is-test-mode": false

Rescuing OpenSSL Errors

An email hit an OpenSSL error that mailgun couldn't rescue because the OpenSSL::SSL::SSLError class doesn't have an http_code method.

2018-01-25T18:30:59.158Z 21699 WARN: NoMethodError: undefined method `http_code' for #<OpenSSL::SSL::SSLError:0x000000082bb2d8>
2018-01-25T18:30:59.158Z 21699 WARN: /usr/local/rvm/gems/ruby-2.4.0/gems/mailgun-0.11/lib/mailgun/base.rb:95:in `rescue in submit'

New release?

How about merging some of the pull requests and wrapping into a new release?

I could really do with some of the new functionality in my project.

Thanks, Darren.

Unable to send messages (using Rails 4)

Great work on the Rails gem. After trying to integrate it with my Rails application I'm stumbling on a couple of problems. What I did to recreate my situation:

  1. Add config to a mailgun.rb initializer:
Mailgun.configure do |config|
  config.api_key = ENV['MAILGUN_API_KEY']
  config.domain  = ENV['MAILGUN_DOMAIN']
end
  1. Trying to send an email from a controller:
    Mailgun.messages.send_email(parameters)

Problems:
It doesn't recognize the messages method.

Things I have tried:
Put Mailgun in an instance variable:

@mailgun = Mailgun()

If I do the above, it asks me for the :domain which I need to set apart from the initializer (huh?). The second downside to this is that I can only make it work by connecting without an initializer directly from the application controller with a before_filter, but that is less from ideal because I don't want to connect again to the Mailgun API every single refresh.

I'm really stuck here, thanks.

Readme problem

image

The "#or alternatively:" part should be something like this:
@mailgun = Mailgun(:domain => ENV['mg-domain'], :api_key => ENV['mg-api-key']) or
@mailgun = Mailgun(:domain => 'your-domain', :api_key => 'your-api-key')

Otherwise will get error like this:
untitled-1

Please consider editing the readme :)


Rails 4.2.1
using in integration with figaro

Gem Lists Wrong Homepage

The link to the homepage in the gem is to a repo that doesn't exist. It was confusing when I was trying to confirm that the code in github was what I was looking at from rubygems :)

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.