• What's new

The Official Mailgun Ruby Gem Is Here

Mailgun Team
5 min read

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:

1require "net/https"
2require "uri"
3
4uri = URI.parse("https://api.mailgun.net/v2/samples.mailgun.org/messages")
5
6data = {'to' => 'joe.sample@example.com',
7 'from' => 'bill.sample@example.com',
8 'subject' => 'Hello from Ruby!',
9 'text' => 'Sent via Mailgun.'}
10
11http = Net::HTTP.new(uri.host, uri.port)
12http.use_ssl = true
13
14request = Net::HTTP::Post.new(uri.request_uri)
15request.basic_auth("api", "key-3ax6xnjp29jd6fds4gc373sgvjxteol0")
16request.set_form_data(data)
17
18response = 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:

1 require 'mailgun'
2
3 # First, instantiate the Mailgun Client with your API key
4 mg_client = Mailgun::Client.new "your-api-key"
5
6 # Define your message parameters
7 message_params = {:from => 'bob@sending_domain.com',
8 :to => 'sally@example.com',
9 :subject => 'The Ruby SDK is awesome!',
10 :text => 'It is really easy to send a message!'}
11
12 # Send your message through the client
13 mg_client.send_message "sending_domain.com", message_params

Obtaining Events with the Mailgun Ruby SDK:

1 # First, instantiate the Client, then instantiate the Events helper.
2 mg_client = Mailgun::Client.new("your-api-key")
3 mg_events = Mailgun::Events.new(mg_client, "your-domain")
4
5 result = mg_events.get({'limit' => 25,
6 'recipient' => 'joe@example.com'})
7
8 result.to_h['items'].each do | item |
9 # outputs "Delivered - 20140509184016.12571.48844@example.com"
10 puts "#{item['event']} - #{item['message']['headers']['message-id']}"
11end

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:

1 # First, instantiate the Mailgun Client with your API key
2 mg_client = Mailgun::Client.new("your-api-key")
3 mb_obj = Mailgun::MessageBuilder.new()
4
5 # Define the from address
6 mb_obj.set_from_address("me@example.com", {"first"=>"Ruby", "last" => "SDK"});
7 # Define a to recipient
8 mb_obj.add_recipient(:to, "john.doe@example.com", {"first" => "John", "last" => "Doe"});
9 # Define a cc recipient
10 mb_obj.add_recipient(:cc, "sally.doe@example.com", {"first" => "Sally", "last" => "Doe"});
11 # Define the subject
12 mb_obj.set_subject("A message from the Ruby SDK using Message Builder!");
13 # Define the body of the message
14 mb_obj.set_text_body("This is the text body of the message!");
15
16 # Campaign and other headers
17 mb_obj.add_campaign_id("My-Awesome-Campaign");
18 mb_obj.add_custom_parameter("h:Customer-Id", "12345");
19
20 # Attach a file and rename it
21 mb_obj.add_attachment("/path/to/file/receipt_123491820.pdf", "Receipt.pdf");
22
23 # Schedule message in the future
24 mb_obj.set_delivery_time("tomorrow 8:00AM", "PST");
25
26 # Finally, send your message using the client
27 result = mg_client.send_message("sending_domain.com", mb_obj)
28
29 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:

1 # First, instantiate the Mailgun Client with your API key
2 mg_client = Mailgun::Client.new("your-api-key")
3 mb_obj = Mailgun::BatchMessage.new(@mb_client, "example.com")
4
5 # Define the from address
6 mb_obj.set_from_address("me@example.com",
7 {"first"=>"Ruby",
8 "last" => "SDK"});
9 # Define the subject
10 mb_obj.set_subject("A message from the Ruby SDK using Message Builder!");
11
12 # Define the body of the message
13 mb_obj.set_text_body("Hello %recipient.first%,
14 This is the text body of the message
15 using recipient variables!
16 If you needed to reference the account-id
17 recipient variable, you could do it like
18 this: %account-id%.");
19
20 # Add several recipients
21 mb_obj.add_recipient(:to, "john.doe@example.com",
22 {"first" => "John",
23 "last" => "Doe",
24 "account-id" => 1234});
25
26 mb_obj.add_recipient(:to, "jane.doe@example.com",
27 {"first" => "Jane",
28 "last" => "Doe",
29 "account-id" => 5678});
30
31 mb_obj.add_recipient(:to, "bob.doe@example.com",
32 {"first" => "Bob",
33 "last" => "Doe",
34 "account-id" => 91011});
35 ... etc ...
36
37 mb_obj.add_recipient(:to, "sally.doe@example.com",
38 {"first" => "Sally",
39 "last" => "Doe",
40 "account-id" => 121314});
41
42 # Send your message through the client
43 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 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 Sending!

sign up

It's easy to get started. And it's free.

What will you accomplish with 10,000 free emails and a 100 free validations every month?

Sign Up For Free

Last updated on August 27, 2019

  • Related posts
  • Recent posts
  • Top posts
View all

Always be in the know and grab free email resources!

No spam, ever. Only musings and writings from the Mailgun team.

Mailgun is committed to protecting your privacy. Please read ourPrivacy Policybefore providing us with your details.

sign up

It's easy to get started. And it's free.

What will you accomplish with 10,000 free emails and a 100 free validations every month?
Sign up for Free