Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting 401 on post request to mailgun api

Im trying to do a post request to send a email, this is my code:

 url = "https://api.mailgun.net/v3/MYDOMAIN/messages"

    params = {
        :from => "Excited User <[email protected]>",
        :to => "[email protected], YOU@YOUR_DOMAIN_NAME",
        :subject => "Hello",
        :text => "Testing some Mailgun awesomness!"
    }

    headers = {
        :api => "MY-API-KEY"
    }

    RestClient.post url, params, headers

When i try to make a request, the response is 401 Unauthorized. Sending the request using HttpRequester works fine(response 200) so my guess is i'm setting headers wrong in Rails. My question: How can i fix this code?

like image 881
Bruno Brito Avatar asked Oct 31 '25 03:10

Bruno Brito


2 Answers

I got a 401 Forbidden because it was using the US server, while I was in the EU. I had to add a line to the MailGun example Go script

// Create an instance of the Mailgun Client 
mg:= mailgun.NewMailgun(yourDomain, privateAPIKey)

/// THIS is the line I had to add to get it to use the EU server.
mg.SetAPIBase(mailgun.APIBaseEU)
like image 156
Howard P Avatar answered Nov 02 '25 17:11

Howard P


Make sure you're using the actual API key you obtained from the dashboard, and not the "key ID" that they emailed you. The two are not the same!

like image 36
Jay Avatar answered Nov 02 '25 17:11

Jay