I’m working on a Django project and using Anymail with Mailgun to send emails.
I have two domains pointing to same site domain1.com and domain2.com
I set up mailgun both senver domains as mg.domain1.com and mg.domain2.com both with their api key.
Both domains worked fine when set as default domain senders.
I need to send client email and switch them depending if they are users of domain1 or domain2. Because I want the serder email will be [email protected] and [email protected] depending on the user.
In my settings.py, I have the following configuration:
ANYMAIL = {
'MAILGUN_API_KEY': API_KEY_DOMAIN1,
'MAILGUN_SENDER_DOMAIN': SENDER_DOMAIN_1'],
}
EMAIL_BACKEND = 'anymail.backends.mailgun.EmailBackend'
SERVER_EMAIL = [email protected]
DEFAULT_FROM_EMAIL = Domain 1 <[email protected]>
Here is send email code:
email = AnymailMessage(
to=message.to.split(','),
cc=message.cc.split(',') if message.cc else None,
bcc=message.bcc.split(',') if message.bcc else None,
reply_to=None,
subject=message.notification.subject,
body=message.notification.body_text,
from_email=message.from_email,
)
email.attach_alternative(message.notification.body_html, 'text/html')
if user.brand['name'] == 'domain2':
email.esp_extra = {
'sender_domain': SENDER_DOMAIN_2,
'api_key': API_KEY_DOMAIN2,
}
try:
email.send()
except Exception as e:
print('Error sending email:', e)
As you can see. I try to use esp_extra to switch between sender domain, but I get:
anymail.exceptions.AnymailRequestsAPIError: Mailgun API response 401 (Unauthorized): 'Forbidden'
What could be causing this issue, and how can I resolve it?