Sending email with mailgun throws 401 Forbidden

Viewed 792

I am trying to send a simple test-email with mailgun and python. And I fail epically. I follow the official documentation and I think I am doing everything correctly but I always get a 401 Forbidden error message.

What I did, let's say my domain name is called bubblegum.de

  1. I set up my domain. I use AWS Route 53, so I follow the instructions and this post https://simpleisbetterthancomplex.com/tutorial/2017/05/27/how-to-configure-mailgun-to-send-emails-in-a-django-app.html

  2. The verification works so I go ahead and create an API key in the settings

  3. Then I go ahead and use the code from the doc to try and send an API

import requests

def send_email():
    try:
        url = "https://api.mailgun.net/v3/mg.bubblegum.de/messages"
        status = requests.post(
            url,
            auth=("api", "MY-BUBBLY-GUMMY-APIKEY"),
            data={"from": "FROM-NAME mg.bubblegum.de",
                  "to":  "bigred@gum.de",
                  "subject": "Tasty bubblegum",
                  "text": "bubble",    
            }          
                  #"html": HTML-TEXT}
        )
        print(status)
        print(status.text)
        return status
    except Exception as e:
        raise e

send_email()

I also tried to use url = "https://api.mailgun.net/v3/bubblegum.de/messages" (without the mg), but same prob.

And now, no matter how many API keys I try I always get 401 Forbidden. And I am pretty sure I am using the correct API-Key :)...

I am sure it must be something with the domain or I am overlooking something... Not sure what I do wrong. Help is very much appreciated. Thanks a bunch!

2 Answers

You did point me to the right direction. I had the same issue, but did not resolve to changing regions, but just used the other endpoints (in my case api.EU.mailgun.net), described here

Ok so I found the problem. Creating this answer if someone runs into the same problem:

I created the mailgun domain in the eu-region and not in the us-region. I did this because my websites end with .de (www.bubblegum.de). Also my DNS provider is European, so I thought this is the way to go.

But, I am using AWS Rout 53 to manage my domains. Deleting the domain and recreating it in the us-region did the trick and everything works as expected. Well, not everything, emails do not arrive to gmx-provider... But this is a pronlem for another day.

Related