Skip to content

Commit

Permalink
Add resend email backend (#166)
Browse files Browse the repository at this point in the history
  • Loading branch information
dimasciput authored Nov 21, 2024
1 parent 5732d9f commit a758e66
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 1 deletion.
94 changes: 94 additions & 0 deletions core/email_backend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import base64
import mimetypes

import requests
from django.core.mail.backends.base import BaseEmailBackend
from django.conf import settings

DEFAULT_FROM_EMAIL = settings.DEFAULT_FROM_EMAIL
RESEND_API_KEY = settings.RESEND_API_KEY


class ResendBackend(BaseEmailBackend):
"""
A Django email backend that uses the Resend API.
"""
def send_messages(self, email_messages):
"""
Send a list of email messages using the Resend API.
:param email_messages: List of Django email messages.
:return: The number of successfully sent messages.
"""
count = 0

for email in email_messages:
response = self._send_via_resend(email)

if response.status_code == 200:
count += 1

return count

def _send_via_resend(self, email):
"""
Send a single email via Resend.
:param email: A Django EmailMessage object.
:return: The response from the Resend API.
"""
resend_api_key = RESEND_API_KEY
from_email = (
DEFAULT_FROM_EMAIL if
DEFAULT_FROM_EMAIL else
email.from_email
)

# Prepare the payload for the Resend API request
payload = {
"from": from_email,
"to": email.to,
"subject": email.subject,
"text": email.body,
}

if email.content_subtype == "html":
payload["html"] = email.body

# Check for HTML content
if email.alternatives:
for alternative in email.alternatives:
content_type, content = alternative
if content_type == "text/html":
payload["html"] = content

attachments = []

for attachment in email.attachments:
if isinstance(attachment, tuple):
filename, content, mime_type = attachment
encoded_content = base64.b64encode(content).decode("utf-8")
else:
filename = attachment
with open(attachment, "rb") as f:
content = f.read()
mime_type, _ = mimetypes.guess_type(filename)
encoded_content = base64.b64encode(content).decode("utf-8")

attachments.append({
"filename": filename,
"content": encoded_content,
"content_type": mime_type,
})

if attachments:
payload["attachments"] = attachments

# Prepare headers
headers = {
"Authorization": f"Bearer {resend_api_key}",
"Content-Type": "application/json",
}

# Make the request to the Resend API
resend_url = "https://api.resend.com/emails"
response = requests.post(resend_url, json=payload, headers=headers)
return response
8 changes: 7 additions & 1 deletion core/settings/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@

LOGIN_REDIRECT_URL = '/'

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_BACKEND = 'core.email_backend.ResendBackend'
ACCOUNT_EMAIL_REQUIRED = True

DBBACKUP_STORAGE_OPTIONS = {'location': 'backups'}
Expand All @@ -200,3 +200,9 @@
"LOCATION": absolute_path('core', 'cache'),
}
}

DEFAULT_FROM_EMAIL = os.environ.get(
'DEFAULT_FROM_EMAIL',
'[email protected]')
RESEND_API_KEY = os.environ.get(
'RESEND_API_KEY', '')

0 comments on commit a758e66

Please sign in to comment.