• Stars
    star
    468
  • Rank 93,751 (Top 2 %)
  • Language
    Ruby
  • License
    Apache License 2.0
  • Created about 11 years ago
  • Updated 26 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Mailgun's Official Ruby Library

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.

More Repositories

1

transactional-email-templates

Responsive transactional HTML email templates
HTML
6,820
star
2

godebug

DEPRECATED! https://github.com/derekparker/delve
Go
2,507
star
3

flanker

Python email address and Mime parsing library
Python
1,633
star
4

talon

Python
1,235
star
5

mailgun-php

Mailgun's Official SDK for PHP
PHP
1,091
star
6

gubernator

High Performance Rate Limiting MicroService and Library
Go
944
star
7

mailgun-js-boland

A simple Node.js helper module for Mailgun API.
JavaScript
896
star
8

kafka-pixy

gRPC/REST proxy for Kafka
Go
752
star
9

mailgun-go

Go library for sending mail with the Mailgun API.
Go
698
star
10

mailgun.js

Javascript SDK for Mailgun
TypeScript
519
star
11

groupcache

Clone of golang/groupcache with TTL and Item Removal support
Go
424
star
12

expiringdict

Dictionary with auto-expiring values for caching purposes.
Python
331
star
13

holster

A place to keep useful golang functions and small libraries
Go
277
star
14

validator-demo

Mailgun email address jquery validation plugin http://mailgun.github.io/validator-demo/
JavaScript
259
star
15

node-prelaunch

A Mailgun powered landing page to capture early sign ups
JavaScript
230
star
16

dnsq

DNS Query Tool
Python
107
star
17

documentation

Mailgun Documentation
CSS
79
star
18

scroll

Scroll is a lightweight library for building Go HTTP services at Mailgun.
Go
61
star
19

kafka-http

Kafka http endpoint
Scala
51
star
20

forge

email dataset for email signature parsing
51
star
21

wordpress-plugin

Mailgun's Wordpress Plugin
PHP
49
star
22

lemma

Mailgun Cryptographic Tools
Go
39
star
23

multibuf

Bytes buffer that implements seeking and partially persisting to disk
Go
37
star
24

ttlmap

In memory dictionary with TTLs
Go
22
star
25

frontend-best-practices

Guides for React and Javascript coding style and best practices
21
star
26

pong

Generates http servers that respond in predefined manner
Go
20
star
27

proxyproto

High performance implementation of V1 and V2 Proxy Protocol
Go
19
star
28

log

Go logging library used at Mailgun.
Go
19
star
29

mailgun-java

Java SDK for integrating with Mailgun
Java
16
star
30

mailgun-meteor-demo

Simple meteor-based emailer with geolocation and UA tracking
JavaScript
16
star
31

timetools

Go library with various time utilities used at Mailgun.
Go
11
star
32

pelican-protocol

In ancient Egypt the pelican was believed to possess the ability to prophesy safe passage in the underworld. Pelicans are ferocious eaters of fish.
Go
11
star
33

metrics

Go library for emitting metrics to StatsD.
Go
11
star
34

roman

Obtain, cache, and automatically reload TLS certificates from an ACME server
Go
10
star
35

sandra

Go library providing some convenience wrappers around gocql.
Go
10
star
36

iptools

Go library providing utilities for working with hosts' IP addresses.
Go
9
star
37

cfg

Go library for working with app's configuration files used at Mailgun.
Go
9
star
38

logrus-hooks

Go
8
star
39

minheap

Slightly more user-friendly heap on top of containers/heap
Go
8
star
40

pebblezgo

go example of the pebblez transport: protocol buffers over zeromq
Go
7
star
41

glogutils

Utils for working with google logging library
Go
7
star
42

pylemma

Mailgun Cryptographic Tools
Python
5
star
43

media

Logos and brand guidelines
4
star
44

callqueue

Serialized call queues
Go
4
star
45

sneakercopy

A tool for creating encrypted tar archives for transferring sensitive data.
Rust
4
star
46

scripts

Example scripts that show how to interact with the Mailgun API
Python
1
star
47

etcd3-slim

Thin wrapper around Etcd3 gRPC stubs
Python
1
star