Search code examples
ruby-on-railscurlrest-clientmailgun

RestClient mailgun error "message": "'from' parameter is missing"


I am using RestClient in my rails app to send emails. The following Curl command works:

    curl -s "https://api:key-XYZ@api.mailgun.net/v2/sandbox30000.mailgun.org/messages" \
    -F from='Mailgun Sandbox <postmaster@sandbox30000.mailgun.org>' \
    -F to='me <my-email-id@gmail.com>'\
    -F subject='Hello XYZ' \
    -F text='Congratulations, you just sent an email with Mailgun!  You are truly awesome!'

But when I try the same using RestClient, I get the following error message:

    error response !!{
      "message": "'from' parameter is missing"
    }

error message !!400 Bad Request

RestClient call:

    RestClient::Request.execute(
    :url => "https://api:key-XYZ@api.mailgun.net/v2/sandbox0000.mailgun.org/messages",
    :method => :post,
    :from => 'Mailgun Sandbox <postmaster@sandbox30000.mailgun.org>',
    :sender => 'Mailgun Sandbox <postmaster@sandbox30000.mailgun.org>',
    :to => "my-email-id@gmail.com",
    :subject => "Hello XYZ",
    :text => "Text body",
    :"h:X-My-Header" => "www/mailgun-email-send",
    :verify_ssl => false)

Solution

  • When you use Request.execute with multiple payload arguments and header(s) you will need to tell RestClient what type of data it is.

    You need to these three fixes to get the equivalent curl-request with RestClient.

    1. Group all post fields into a payload hash
    2. Add the single header into a header hash
    3. Tell RestClient that the payload should be sent as multipart.

    The changed request:

    RestClient::Request.execute(
      :url => "https://api:key-XYZ@api.mailgun.net/v2/sandbox0000.mailgun.org/messages",
      :method => :post,
      :payload => {
        :from => 'Mailgun Sandbox <postmaster@sandbox30000.mailgun.org>',
        :sender => 'Mailgun Sandbox <postmaster@sandbox30000.mailgun.org>',
        :to => "my-email-id@gmail.com",
        :subject => "Hello XYZ",
        :text => "Text body",
        :multipart => true
      },
      :headers => {
        :"h:X-My-Header" => "www/mailgun-email-send"
      },
      :verify_ssl => false
    )