- Best Practices
How To Avoid Emails Going To Spam
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"34uri = URI.parse("https://api.mailgun.net/v2/samples.mailgun.org/messages")56data = {'to' => 'joe.sample@example.com', 7 'from' => 'bill.sample@example.com',8 'subject' => 'Hello from Ruby!',9 'text' => 'Sent via Mailgun.'}1011http = Net::HTTP.new(uri.host, uri.port) 12http.use_ssl = true1314request = Net::HTTP::Post.new(uri.request_uri) 15request.basic_auth("api", "key-3ax6xnjp29jd6fds4gc373sgvjxteol0") 16request.set_form_data(data)1718response = 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 key4 mg_client = Mailgun::Client.new "your-api-key"5 6 # Define your message parameters7 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 client13 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”.
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 address6 mb_obj.set_from_address("me@example.com", {"first"=>"Ruby", "last" => "SDK"}); 7 # Define a to recipient8 mb_obj.add_recipient(:to, "john.doe@example.com", {"first" => "John", "last" => "Doe"}); 9 # Define a cc recipient10 mb_obj.add_recipient(:cc, "sally.doe@example.com", {"first" => "Sally", "last" => "Doe"}); 11 # Define the subject12 mb_obj.set_subject("A message from the Ruby SDK using Message Builder!"); 13 # Define the body of the message14 mb_obj.set_text_body("This is the text body of the message!");15 16 # Campaign and other headers17 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 it21 mb_obj.add_attachment("/path/to/file/receipt_123491820.pdf", "Receipt.pdf");22 23 # Schedule message in the future24 mb_obj.set_delivery_time("tomorrow 8:00AM", "PST");25 26 # Finally, send your message using the client27 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.
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 address6 mb_obj.set_from_address("me@example.com", 7 {"first"=>"Ruby", 8 "last" => "SDK"});9 # Define the subject10 mb_obj.set_subject("A message from the Ruby SDK using Message Builder!");11 12 # Define the body of the message13 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-id17 recipient variable, you could do it like 18 this: %account-id%.");19 20 # Add several recipients21 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 client43 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.
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!
It's easy to get started. And it's free.
See what you can accomplish with the world’s best email delivery platform.
Last updated on August 28, 2020
How To Avoid Emails Going To Spam
Which SMTP Port Should I Use? Understanding Ports 25, 465, & 587
How To Use Parallel Programming
The Best Time to Send Holiday Emails - Investigated
Building the Best Email Experience for Creators - Flipsnack’s Story
Where is my email going? Introducing Inbox Placement
How we built a Lucene-inspired parser in Go
Gubernator: Cloud-native distributed rate limiting for microservices
Email Burst Dos And Don’ts
Email Blasts: The Do’s And Many Don’ts Of Mass Email Sending
Mailpets: For The Love Of Animals
Make Email Accessibility Your New Year’s Resolution
Sunset Policies: Allowing Unengaged Recipients to Ride Off into the Sunset
Email's Best of 2020
Catch-All Domain Support Is Now Available In Email Validations
The Best Time To Send Emails: Cracking The Code
Tips for Building Better Holiday Email Templates
Happy Festivus: Email Deliverability For The Holiday Season
The Basics of Email Subdomains
A Word of Caution For Laravel Developers
Make Email Accessibility Your New Year’s Resolution
Sunset Policies: Allowing Unengaged Recipients to Ride Off into the Sunset
Email's Best of 2020
How To Improve Email Open Rates
Preparing Your Email Infrastructure Correctly
4 Tips To Improve Your Email Deliverability In 2020
COVID-19 Email Communications Dos and Don’ts
How To Use Parallel Programming
Mailgun’s COVID-19 Plan of Action
Password Meters Are Not For Humans
Always be in the know and grab free email resources!
Mailgun is committed to protecting your privacy. Please read ourPrivacy Policybefore providing us with your details.