Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby mailgun send mail fails with 400 bad request

Tags:

ruby

mailgun

I'm trying out mailgun API with ruby. First thing I did was register an account. I have the api_key and the sandbox domain active. I then add my own email to authorized recipients from the sandbox domain. I did exactly like in the docs:

def send_simple_message
  RestClient.post "https://api:key-mykey"\
  "@api.mailgun.net/v3/sandboxe5148e9bfa2d4e99a1b02d237a8546fe.mailgun.org/messages",
  :from => "Excited User <[email protected]>",
  :to => "[email protected], [email protected]",
  :subject => "Hello",
  :text => "Testing some Mailgun awesomness!",
  :multipart => true
end

send_simple_message

But it always returns 400 bad request, here's the trace from the terminal:

/home/ys/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rest-client-2.0.0/lib/restclient/abstract_response.rb:223:in `exception_with_response': 400 Bad Request (RestClient::BadRequest)
    from /home/ys/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rest-client-2.0.0/lib/restclient/abstract_response.rb:103:in `return!'
    from /home/ys/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rest-client-2.0.0/lib/restclient/request.rb:860:in `process_result'
    from /home/ys/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rest-client-2.0.0/lib/restclient/request.rb:776:in `block in transmit'
    from /home/ys/.rbenv/versions/2.3.1/lib/ruby/2.3.0/net/http.rb:853:in `start'
    from /home/ys/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rest-client-2.0.0/lib/restclient/request.rb:766:in `transmit'
    from /home/ys/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rest-client-2.0.0/lib/restclient/request.rb:215:in `execute'
    from /home/ys/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rest-client-2.0.0/lib/restclient/request.rb:52:in `execute'
    from /home/ys/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rest-client-2.0.0/lib/restclient.rb:71:in `post'
    from mailgunner.rb:24:in `send_simple_message'
    from mailgunner.rb:33:in `<main>'

What did I do wrong here? I installed rest-client gem so I think there's some problems in my registration or something?

like image 976
fatg Avatar asked Jul 15 '16 05:07

fatg


1 Answers

I had a similar problem and saw the documentation here: https://github.com/rest-client/rest-client (in the exceptions section) where they surrounded the RestClient.post with a rescue. And I made it print:

 def send_simple_message
   begin
     RestClient.post ...
   rescue RestClient::ExceptionWithResponse => e
     puts e.response
   end
 end

then I got an error string with this:

{"message": "'from' parameter is not a valid address. please check documentation"}

then saw that in my test I had an error in the from field:

:from => "Test <[email protected]", # missing '>' at the end 

Maybe you can use a similar approach, to solve your problem.

like image 181
João Reis Avatar answered Sep 20 '22 23:09

João Reis