Sending Emails with Mailgun

The Mailgun API is built on HTTP and is RESTful. It uses predictable, resource- oriented URLs and built-in HTTP capabilities for passing parameters and authentication. The Mailgun API responds with standard HTTP response codes to indicate errors, and returns JSON.

Mailgun has published libraries for various languages. You can use these libraries or your favorite HTTP/REST library to make HTTP calls to Mailgun.

For more code samples in other programming languages, see Mailgun's documentation.

Pricing

As a Google Cloud Platform user, your first 30,000 messages are free every month. See the monthly pricing calculator on the sign up page for pricing on additional messages and volume discounts.

Setup

Examples

Sending a plain text message:

# Send simple plaintext email message
post "/send/plaintext_email" do
  mailgun = Mailgun::Client.new MAILGUN_API_KEY

  mailgun.send_message MAILGUN_DOMAIN_NAME,
                       to:      params[:recipient],
                       from:    "Mailgun User <mailgun@#{MAILGUN_DOMAIN_NAME}>",
                       subject: "Simple Mailgun Example",
                       text:    "Plaintext content"

  "Email sent."
end

Sending a message with HTML and text parts. This example also attaches files to the message:

# Send HTML email message with attachment
post "/send/complex_email" do
  mailgun = Mailgun::Client.new MAILGUN_API_KEY
  message = Mailgun::MessageBuilder.new

  message.add_recipient  :to, params[:recipient]
  message.add_recipient  :from, "Mailgun User <mailgun@#{MAILGUN_DOMAIN_NAME}>"
  message.subject        "Complex Mailgun Example"
  message.body_text      "Plaintext content"
  message.body_html      "<html>HTML <strong>content</strong></html>"
  message.add_attachment "./example-attachment.txt", "attachment"

  mailgun.send_message MAILGUN_DOMAIN_NAME, message

  "Email sent."
end

Sample response:

{
    "message": "Queued. Thank you.",
    "id": "<20111114174239.25659.5817@samples.mailgun.org>"
}

Learning more

For more detailed examples and information, including how to track and route messages, see Mailgun's documentation.

Send feedback about...

App Engine flexible environment for Ruby docs