- Best Practices
Email Blasts: The Dos And Many Don’ts Of Mass Email Sending
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!
Learn about our Deliverability Services
Looking to send a high volume of emails? Our email experts can supercharge your email performance. See how we've helped companies like Lyft, Shopify, Github increase their email delivery rates to an average of 97%.
Last updated on August 28, 2020
Email Blasts: The Dos And Many Don’ts Of Mass Email Sending
The Difference Between SMTP and API
The Basics of Email Dark Mode
COVID-19 Survey: How the Pandemic Has Affected Email Sending
The Top Email Clients and Email Apps of 2021
The Benefits of Email Automation
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
InboxReady x Salesforce: The Key to a Stronger Email Deliverability
Become an Email Pro With Our Templates API
Google Postmaster Tools: Understanding Sender Reputation
Navigating Your Career as a Woman in Tech
Implementing Dmarc – A Step-by-Step Guide
Email Bounces: What To Do About Them
Announcing InboxReady: The deliverability suite you need to hit the inbox
Black History Month in Tech: 7 Visionaries Who Shaped The Future
How To Create a Successful Triggered Email Program
Designing HTML Email Templates For Transactional Emails
InboxReady x Salesforce: The Key to a Stronger Email Deliverability
Implementing Dmarc – A Step-by-Step Guide
Announcing InboxReady: The deliverability suite you need to hit the inbox
Designing HTML Email Templates For Transactional Emails
Email Security Best Practices: How To Keep Your Email Program Safe
Mailgun’s Active Defense Against Log4j
Email Blasts: The Dos And Many Don’ts Of Mass Email Sending
Email's Best of 2021
5 Ideas For Better Developer-Designer Collaboration
Mailgun Joins Sinch: The Future of Customer Communications Is Here
Always be in the know and grab free email resources!
By sending this form, I agree that Mailgun may contact me and process my data in accordance with its Privacy Policy.