This add-on is operated by Mailgun Technologies, Inc.
The email service provider for technologically progressive businesses.
Mailgun
Last updated August 16, 2021
Table of Contents
Unlike other cloud email providers, Mailgun offers a complete email service built for sending, receiving, tracking and storing email.
Deploying to Heroku
To use Mailgun on Heroku, install the Mailgun add-on and select the Mailgun plan you want to use:
$ heroku addons:create mailgun:<PLAN>
Sending emails via SMTP
Here is a sample configuration for ActionMailer.
ActionMailer::Base.smtp_settings = {
:port => ENV['MAILGUN_SMTP_PORT'],
:address => ENV['MAILGUN_SMTP_SERVER'],
:user_name => ENV['MAILGUN_SMTP_LOGIN'],
:password => ENV['MAILGUN_SMTP_PASSWORD'],
:domain => 'yourapp.heroku.com',
:authentication => :plain,
}
ActionMailer::Base.delivery_method = :smtp
You can also consider using alternative SMTP frameworks such as Pony
Sending emails via HTTP
SMTP works great for sending emails but this protocol requires you to prepare your messages in MIME format. And learning the details of MIME is not fun.
Mailgun HTTP-based sending API provides a much simpler alternative. Instead of dealing with MIME libraries, simply post parameters via HTTP to us. What parameters? The ones you would expect: “From”, “To”, “Cc”, “Bcc”, “Subject” and so on. The same stuff Gmail GUI uses.
Consider the following example which uses rest-client gem to perform an HTTP request:
require 'rest-client'
API_KEY = ENV['MAILGUN_API_KEY']
API_URL = "https://api:#{API_KEY}@api.mailgun.net/v2/<your-mailgun-domain>"
RestClient.post API_URL+"/messages",
:from => "ev@example.com",
:to => "ev@mailgun.net",
:subject => "This is subject",
:text => "Text body",
:html => "<b>HTML</b> version of the body!"
The example above is very basic. HTTP API supports many advanced features such as file uploads, sending in test mode and more. See API Documentation for more information.
Receiving messages via HTTP
Mailgun allows you to define a flexible set of rules for how to handle incoming emails. One popular option is to parse the incoming messages and post them into your application via HTTP. Click here to read more about receiving.
In addition to basic email parsing, Mailgun will optionally perform the following:
- Spam filtering
- Separation of quoted part of the email from the actual body
- Signature detection
Here is an example of a Rails action which receives incoming mail via Mailgun:
class EmailsController < ApplicationController
skip_before_filter :verify_authenticity_token
def post
# process various message parameters:
sender = params['from']
subject = params['subject']
# get the "stripped" body of the message, i.e. without
# the quoted part
actual_body = params["stripped-text"]
# process all attachments:
count = params['attachment-count'].to_i
count.times do |i|
stream = params["attachment-#{i+1}"]
filename = stream.original_filename
data = stream.read()
end
render :text => "OK"
end
end