The official Mailgun Ruby Gem is here

Today, we're happy to announce that we've added Ruby to the list of official Mailgun SDKs.  Just like our PHP SDK, we've included some utilities like Message Builder, Batch Sending and Opt-in Hander to simplify common development tasks.  We're looking forward to collaborating with the Ruby community to make the SDK even better over time.  You can access the SDK on Github.

For those not familiar with an SDK, let's first review what's required to send a message using the standard HTTPS Ruby library.

Sending a message:

require "net/https"  
require "uri"

uri = URI.parse("https://api.mailgun.net/v2/samples.mailgun.org/messages")

data = {'to'        => 'joe.sample@example.com',  
        'from'      => 'bill.sample@example.com',
        'subject'   => 'Hello from Ruby!',
        'text'      => 'Sent via Mailgun.'}

http = Net::HTTP.new(uri.host, uri.port)  
http.use_ssl = true

request = Net::HTTP::Post.new(uri.request_uri)  
request.basic_auth("api", "key-3ax6xnjp29jd6fds4gc373sgvjxteol0")  
request.set_form_data(data)

response = http.request(request)  

The above will send a message using the Mailgun API, however, there's a lot of code there that, while important, is complicated, and rather confusing.

Using our new SDK, we've managed to reduce the amount of code required to just a few lines.

Sending a message with Mailgun Ruby SDK:

require 'mailgun'

# 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      => 'sally@example.com',
                  :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

Obtaining Events with the Mailgun Ruby SDK:

# First, instantiate the Client, then instantiate the Events helper.  
mg_client = Mailgun::Client.new("your-api-key")  
mg_events = Mailgun::Events.new(mg_client, "your-domain")

result = mg_events.get({'limit' => 25,  
                        'recipient' => 'joe@example.com'})

result.to_h['items'].each do | item |  
    # outputs "Delivered - 20140509184016.12571.48844@example.com"
    puts "#{item['event']} - #{item['message']['headers']['message-id']}"
end

All HTTP actions return a response object, which can be converted to a hash or YAML.

Let's say we'd like to get the next 25 results, using the same query. Just issue "next" on the "mg_events" object. The SDK keeps track of the Events API pagination links.

result = mg_events.next

Note: If the result set is less than your limit, do not worry. A subsequent query of "next" will return the next 25 results since the last time you called "next" or "get".

Message Builder

Creating an array of parameters can be difficult for some code implementations, so we've included a class that allows you to make method calls that automatically build a properly formed array of message parameters.

Sending a message with Mailgun Ruby SDK + Message Builder:

# First, instantiate the Mailgun Client with your API key  
mg_client = Mailgun::Client.new("your-api-key")  
mb_obj = Mailgun::MessageBuilder.new()

# Define the from address
mb_obj.set_from_address("me@example.com", {"first"=>"Ruby", "last" => "SDK"});  
# Define a to recipient
mb_obj.add_recipient(:to, "john.doe@example.com", {"first" => "John", "last" => "Doe"});  
# Define a cc recipient
mb_obj.add_recipient(:cc, "sally.doe@example.com", {"first" => "Sally", "last" => "Doe"});  
# Define the subject
mb_obj.set_subject("A message from the Ruby SDK using Message Builder!");  
# Define the body of the message
mb_obj.set_text_body("This is the text body of the message!");

# Campaign and other headers
mb_obj.add_campaign_id("My-Awesome-Campaign");  
mb_obj.add_custom_parameter("h:Customer-Id", "12345");

# Attach a file and rename it
mb_obj.add_attachment("/path/to/file/receipt_123491820.pdf", "Receipt.pdf");

# Schedule message in the future
mb_obj.set_delivery_time("tomorrow 8:00AM", "PST");

# Finally, send your message using the client
result = mg_client.send_message("sending_domain.com", mb_obj)

puts result.body.to_s

For a list of all available functions, check out the list on Github.

Batch Message

In addition to Message Builder, we have Batch Message. This class allows you to build a message and submit a template message in batches, up to 1,000 recipients per post. The benefit of using this class is that the recipients tally is monitored and will automatically submit the message to the endpoint when you've added the 1,000th recipient. This means you can build your message and begin iterating through your database. Forget about sending the message, the SDK will keep track of posting to the API when necessary.

Sending a message with Mailgun Ruby SDK + Batch Message:

# First, instantiate the Mailgun Client with your API key  
mg_client = Mailgun::Client.new("your-api-key")  
mb_obj = Mailgun::BatchMessage.new(@mb_client, "example.com")

# Define the from address
mb_obj.set_from_address("me@example.com",  
                                 {"first"=>"Ruby", 
                                  "last" => "SDK"});
# Define the subject
mb_obj.set_subject("A message from the Ruby SDK using Message Builder!");

# Define the body of the message
mb_obj.set_text_body("Hello %recipient.first%,  
                     This is the text body of the message 
                     using recipient variables!
                     If you needed to reference the account-id
                     recipient variable, you could do it like 
                     this: %account-id%.");

# Add several recipients
mb_obj.add_recipient(:to, "john.doe@example.com",  
                                      {"first"      => "John", 
                                       "last"       => "Doe", 
                                       "account-id" => 1234});

mb_obj.add_recipient(:to, "jane.doe@example.com",  
                                      {"first"      => "Jane", 
                                       "last"       => "Doe", 
                                       "account-id" => 5678});

mb_obj.add_recipient(:to, "bob.doe@example.com",  
                                      {"first"       => "Bob", 
                                       "last"        => "Doe", 
                                       "account-id"  => 91011});
... etc ...

mb_obj.add_recipient(:to, "sally.doe@example.com",  
                                      {"first"      => "Sally", 
                                       "last"       => "Doe", 
                                       "account-id" => 121314});

# Send your message through the client
message_ids = mg_client.finalize

As you can see, Batch Message actually extends Message Builder. All functions available in Message Builder are available in Batch Message. Check out the full documentation on Github.

Opt-In Handler

Finally, we have built a simple double opt-in handler to help you generate unique opt-in links. The opt-in handler also uses our free address validation service to validate the accuracy of the email addresses.

The typical flow for using this class would be as follows:
Recipient Requests Subscribe -> [Validate Recipient Address] -> [Generate Opt In Link] -> [Email Recipient Opt In Link]
Recipient Clicks Opt In Link -> [Validate Opt In Link] -> [Subscribe User] -> [Send final confirmation]

It is best to use this class for your website subscription forms, so you'll need a web server accessible to the internet to handle the validation link click.

Since each implementation will be rather unique, see the Github documentation for usage examples of this class.

Let us know what you think.  Is there something else you'd like to see in the SDK?  Or something you love. We'd appreciate your feedback!

Happy emailing,

The Mailgunners

 

comments powered by Disqus

Mailgun Get posts by email

Like what you're reading? Get these posts delivered to your inbox.

No spam, ever.