djangosmtpmailgundjango-anymaildjango-mailgun

Django Mailgun API returning 401 forbidden


I've installed Django any mail and am I trying to use mail gun with it for password resets. I've added any mail to my installed apps and tried to use mail gun as an API or smtp service. Both return back 401 forbidden

For using mail guns API here's my code:

EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend"
ANYMAIL_MAILGUN_API_KEY = config("MAIL_GUN_DOMAIN_API")

For MAIL_GUN_DOMAIN_API I tried using my accounts private key and I tried creating a domain and using the domains sending key. Both returned the same response.

for smtp :

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.mailgun.org'
EMAIL_PORT = 465
EMAIL_HOST_USER = config('MAIL_GUN_USERNAME')
EMAIL_HOST_PASSWORD = config('MAIL_GUN_SMTP_PASSWORD')
EMAIL_USE_TLS = True 

for MAIL_GUN_USERNAME I used my domains login for MAIL_GUN_SMTP_PASSWORD I used my domains password I tried all of mailguns different ports and switching between tls and ssl none of this worked.

Any ideas what I'm doing wrong?


Solution

  • The 401 error means your API key wasn't valid for the email you were trying to send. There are three likely possibilities:

    1. The From address for the emails you're sending doesn't match your Mailgun sending domain. Check that Django's DEFAULT_FROM_EMAIL is set to an address you're allowed to send from. (The default is "webmaster@localhost", which definitely won't work.)

      You might also want to look into Anymail's MAILGUN_SENDER_DOMAIN setting, depending on what emails you're trying to use and how your Mailgun account is set up.

    2. The API_KEY or PASSWORD you're reading from config() is incorrect. If you're getting your config from an .env file, a common mistake is trying to include a comment on the line with the key/password, which many versions of .env don't support. This won't work:

      # In a .env file, comments should be on a separate line.
      MAIL_GUN_DOMAIN_API=mg-key-abcdefg  # comment not allowed here!
      
    3. If you provisioned your sending domain in Mailgun's EU zone, you'll need to point Anymail to Mailgun's EU API servers instead of the default US servers. See Anymail's MAILGUN_API_URL setting. (I don't think this would affect SMTP, though.)