Noel-Teens commited on
Commit
ffedc01
·
1 Parent(s): 4927596

resend api implementation

Browse files
Files changed (3) hide show
  1. admin_app/views.py +41 -35
  2. pms_server/settings.py +5 -5
  3. requirements.txt +2 -1
admin_app/views.py CHANGED
@@ -24,6 +24,8 @@ from django.core.mail import EmailMultiAlternatives
24
  from django.template.loader import render_to_string
25
  from django.utils import timezone
26
  import os
 
 
27
  import zipfile
28
  import base64
29
  from django.http import FileResponse, Http404, JsonResponse, HttpResponseNotFound
@@ -60,47 +62,51 @@ import logging
60
 
61
  logger = logging.getLogger(__name__)
62
 
63
-
64
  def _send_invite_email(email: str, invite_link: str, inviter: str = None):
65
- """Send an HTML + text email using Resend SMTP with fallback."""
66
  subject = "You're invited to join Project Management System"
67
- text_content = f"You have been invited to join the Project Management System. Click the link to accept: {invite_link}"
68
- html_content = render_to_string("emails/invite.html", {"invite_link": invite_link, "inviter": inviter})
 
 
 
 
 
69
 
70
  try:
71
- # Use Resend SMTP with professional from address
72
- msg = EmailMultiAlternatives(
73
- subject=subject,
74
- body=text_content,
75
- from_email=settings.DEFAULT_FROM_EMAIL, # "PMS <noreply@neurostack.com>"
76
- to=[email]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  )
78
- msg.attach_alternative(html_content, "text/html")
79
- msg.send()
80
- logger.info(f"Invitation email sent successfully to {email} via Resend SMTP")
81
-
 
 
 
 
 
82
  except Exception as e:
83
- logger.error(f"Failed to send email via Resend SMTP to {email}: {str(e)}")
84
-
85
- # Fallback to console backend for development/testing
86
- try:
87
- from django.core.mail.backends.console import EmailBackend
88
- console_backend = EmailBackend()
89
-
90
- msg = EmailMultiAlternatives(
91
- subject=subject,
92
- body=text_content,
93
- from_email=settings.DEFAULT_FROM_EMAIL,
94
- to=[email],
95
- connection=console_backend
96
- )
97
- msg.attach_alternative(html_content, "text/html")
98
- msg.send()
99
- logger.warning(f"Email sent to {email} via console fallback due to SMTP failure")
100
-
101
- except Exception as fallback_error:
102
- logger.error(f"Both SMTP and console fallback failed for {email}: {str(fallback_error)}")
103
- raise Exception(f"Email sending failed: {str(e)}")
104
 
105
  @csrf_exempt
106
  @api_view(["POST"])
 
24
  from django.template.loader import render_to_string
25
  from django.utils import timezone
26
  import os
27
+ import requests
28
+ import resend
29
  import zipfile
30
  import base64
31
  from django.http import FileResponse, Http404, JsonResponse, HttpResponseNotFound
 
62
 
63
  logger = logging.getLogger(__name__)
64
 
 
65
  def _send_invite_email(email: str, invite_link: str, inviter: str = None):
66
+ """Send an invitation email using Resend API (works on Hugging Face)."""
67
  subject = "You're invited to join Project Management System"
68
+ html_content = render_to_string(
69
+ "emails/invite.html", {"invite_link": invite_link, "inviter": inviter}
70
+ )
71
+ text_content = (
72
+ f"You have been invited to join the Project Management System.\n\n"
73
+ f"Click the link to accept: {invite_link}"
74
+ )
75
 
76
  try:
77
+ api_key = os.getenv("RESEND_API_KEY")
78
+ if not api_key:
79
+ raise Exception("RESEND_API_KEY not set in environment.")
80
+
81
+ from_email = os.getenv("RESEND_FROM_EMAIL", "onboarding@resend.dev")
82
+
83
+ response = requests.post(
84
+ "https://api.resend.com/emails",
85
+ headers={
86
+ "Authorization": f"Bearer {api_key}",
87
+ "Content-Type": "application/json",
88
+ },
89
+ json={
90
+ "from": from_email,
91
+ "to": [email],
92
+ "subject": subject,
93
+ "text": text_content,
94
+ "html": html_content,
95
+ },
96
+ timeout=10,
97
  )
98
+
99
+ resp_data = response.json()
100
+ if response.status_code != 200:
101
+ logger.error(f"Resend API error {response.status_code}: {resp_data}")
102
+ raise Exception(f"Resend API error {response.status_code}: {resp_data}")
103
+
104
+ logger.info(f"Invitation email sent successfully to {email}")
105
+ return resp_data
106
+
107
  except Exception as e:
108
+ logger.error(f"Failed to send email to {email}: {str(e)}")
109
+ raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
  @csrf_exempt
112
  @api_view(["POST"])
pms_server/settings.py CHANGED
@@ -13,6 +13,7 @@ https://docs.djangoproject.com/en/5.2/ref/settings/
13
  from pathlib import Path
14
  import os
15
  from datetime import timedelta
 
16
  from dotenv import load_dotenv
17
 
18
  load_dotenv()
@@ -251,12 +252,11 @@ CORS_ALLOW_PRIVATE_NETWORK = True
251
 
252
  APPEND_SLASH=False
253
 
 
 
 
254
  # Email configuration using Resend SMTP
255
- EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
256
- EMAIL_HOST = "smtp.resend.com"
257
- EMAIL_PORT = 587
258
- EMAIL_USE_TLS = True
259
- EMAIL_HOST_USER = "resend"
260
  EMAIL_HOST_PASSWORD = os.getenv("RESEND_API_KEY")
261
 
262
  # Professional from address format
 
13
  from pathlib import Path
14
  import os
15
  from datetime import timedelta
16
+ import resend
17
  from dotenv import load_dotenv
18
 
19
  load_dotenv()
 
252
 
253
  APPEND_SLASH=False
254
 
255
+ RESEND_API_KEY = os.getenv("RESEND_API_KEY")
256
+ resend.api_key = RESEND_API_KEY
257
+
258
  # Email configuration using Resend SMTP
259
+ EMAIL_BACKEND = "django.core.mail.backends.base.BaseEmailBackend"
 
 
 
 
260
  EMAIL_HOST_PASSWORD = os.getenv("RESEND_API_KEY")
261
 
262
  # Professional from address format
requirements.txt CHANGED
@@ -5,4 +5,5 @@ firebase-admin
5
  djangorestframework-simplejwt
6
  uvicorn==0.34.0
7
  asgiref==3.8.1
8
- dotenv
 
 
5
  djangorestframework-simplejwt
6
  uvicorn==0.34.0
7
  asgiref==3.8.1
8
+ dotenv
9
+ resend