Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

[Feat] V2 Emails - Fixes for sending emails when creating keys + Resend API support (#10602)

Ishaan Jaffdd32860d622a
diff --git a/enterprise/enterprise_callbacks/send_emails/base_email.py b/enterprise/enterprise_callbacks/send_emails/base_email.py
new file mode 100644
index 00000000000..1b9b601738a
--- /dev/null
+++ b/enterprise/enterprise_callbacks/send_emails/base_email.py
@@ -0,0 +1,104 @@
+"""
+Base class for sending emails to user after creating keys or invite links
+
+"""
+
+import json
+import os
+from typing import List, Optional
+
+from litellm._logging import verbose_proxy_logger
+from litellm.integrations.custom_logger import CustomLogger
+from litellm.integrations.email_templates.key_created_email import (
+ KEY_CREATED_EMAIL_TEMPLATE,
+)
+from litellm.types.enterprise.enterprise_callbacks.send_emails import (
+ SendKeyCreatedEmailEvent,
+)
+from litellm.types.integrations.slack_alerting import LITELLM_LOGO_URL
+
+
+class BaseEmailLogger(CustomLogger):
+ DEFAULT_LITELLM_EMAIL = "[email protected]"
+ DEFAULT_SUPPORT_EMAIL = "[email protected]"
+
+ async def send_key_created_email(
+ self, send_key_created_email_event: SendKeyCreatedEmailEvent
+ ):
+ """
+ Send email to user after creating key for the user
+ """
+ email_logo_url = os.getenv("EMAIL_LOGO_URL", None) or LITELLM_LOGO_URL
+ email_support_contact = os.getenv(
+ "EMAIL_SUPPORT_CONTACT", self.DEFAULT_SUPPORT_EMAIL
+ )
+ base_url = os.getenv("PROXY_BASE_URL", "http://0.0.0.0:4000")
+
+ recipient_email: Optional[str] = (
+ send_key_created_email_event.user_email
+ or await self._lookup_user_email_from_db(
+ user_id=send_key_created_email_event.user_id
+ )
+ )
+ if recipient_email is None:
+ raise ValueError(
+ f"User email not found for user_id: {send_key_created_email_event.user_id}. User email is required to send email."
+ )
+
+ verbose_proxy_logger.debug(
+ f"send_key_created_email_event: {json.dumps(send_key_created_email_event, indent=4, default=str)}"
+ )
+
+ email_html_content = KEY_CREATED_EMAIL_TEMPLATE.format(
+ email_logo_url=email_logo_url,
+ recipient_email=recipient_email,
+ key_budget=self._format_key_budget(send_key_created_email_event.max_budget),
+ key_token=send_key_created_email_event.virtual_key,
+ base_url=base_url,
+ email_support_contact=email_support_contact,
+ )
+
+ await self.send_email(
+ from_email=self.DEFAULT_LITELLM_EMAIL,
+ to_email=[recipient_email],
+ subject=f"LiteLLM: {send_key_created_email_event.event_message}",
+ html_body=email_html_content,
+ )
+ pass
+
+ def _format_key_budget(self, max_budget: Optional[float]) -> str:
+ """
+ Format the key budget to be displayed in the email
+ """
+ if max_budget is None:
+ return "No budget"
+ return f"${max_budget}"
+
+ async def _lookup_user_email_from_db(self, user_id: Optional[str]) -> Optional[str]:
+ """
+ Lookup user email from user_id
+ """
+ from litellm.proxy.proxy_server import prisma_client
+
+ if prisma_client is None:
+ verbose_proxy_logger.debug(
+ f"Prisma client not found. Unable to lookup user email for user_id: {user_id}"
+ )
+ return None
+
+ user_row = await prisma_client.db.litellm_usertable.find_unique(
+ where={"user_id": user_id}
+ )
+
+ if user_row is not None:
+ return user_row.user_email
+ return None
+
+ async def send_email(
+ self,
+ from_email: str,
+ to_email: List[str],
+ subject: str,
+ html_body: str,
+ ):
+ pass
diff --git a/enterprise/enterprise_callbacks/send_emails/resend_email.py b/enterprise/enterprise_callbacks/send_emails/resend_email.py
new file mode 100644
index 00000000000..8119e4a7ef5
--- /dev/null
+++ b/enterprise/enterprise_callbacks/send_emails/resend_email.py
@@ -0,0 +1,51 @@
+"""
+This is the litellm x resend email integration
+
+https://resend.com/docs/api-reference/emails/send-email
+"""
+
+import os
+from typing import List
+
+from litellm._logging import verbose_logger
+from litellm.llms.custom_httpx.http_handler import (
+ get_async_httpx_client,
+ httpxSpecialProvider,
+)
+
+from .base_email import BaseEmailLogger
+
+RESEND_API_ENDPOINT = "https://api.resend.com/emails"
+
+
+class ResendEmailLogger(BaseEmailLogger):
+ def __init__(self):
+ self.async_httpx_client = get_async_httpx_client(
+ llm_provider=httpxSpecialProvider.LoggingCallback
+ )
+ self.resend_api_key = os.getenv("RESEND_API_KEY")
+
+ async def send_email(
+ self,
+ from_email: str,
+ to_email: List[str],
+ subject: str,
+ html_body: str,
+ ):
+ verbose_logger.debug(
+ f"Sending email from {from_email} to {to_email} with subject {subject}"
+ )
+ response = await self.async_httpx_client.post(
+ url=RESEND_API_ENDPOINT,
+ json={
+ "from": from_email,
+ "to": to_email,
+ "subject": subject,
+ "html": html_body,
+ },
+ headers={"Authorization": f"Bearer {self.resend_api_key}"},
+ )
+ verbose_logger.debug(
+ f"Email sent with status code {response.status_code}. Got response: {response.json()}"
+ )
+ return
diff --git a/litellm/__init__.py b/litellm/__init__.py
index 196e00f587e..a08230c6ed8 100644
--- a/litellm/__init__.py
+++ b/litellm/__init__.py
@@ -116,6 +116,7 @@ _custom_logger_compatible_callbacks_literal = Literal[
"anthropic_cache_control_hook",
"bedrock_vector_store",
"generic_api",
+ "resend_email",
]
logged_real_time_event_types: Optional[Union[List[str], Literal["*"]]] = None
_known_custom_logger_compatible_callbacks: List = list(
diff --git a/litellm/integrations/email_templates/key_created_email.py b/litellm/integrations/email_templates/key_created_email.py
new file mode 100644
index 00000000000..a292223db27
--- /dev/null
+++ b/litellm/integrations/email_templates/key_created_email.py
@@ -0,0 +1,219 @@
+"""
+Modern Email Templates for LiteLLM Email Service with professional styling
+"""
+
+KEY_CREATED_EMAIL_TEMPLATE = """
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Your API Key is Ready</title>
+ <style>
+ body, html {{
+ margin: 0;
+ padding: 0;
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
+ color: #333333;
+ background-color: #f8fafc;
+ line-height: 1.5;
+ }}
+ .container {{
+ max-width: 560px;
+ margin: 20px auto;
+ background-color: #ffffff;
+ border-radius: 8px;
+ overflow: hidden;
+ box-shadow: 0 1px 3px rgba(0,0,0,0.1);
+ }}
+ .header {{
+ padding: 24px 0;
+ text-align: center;
+ border-bottom: 1px solid #f1f5f9;
+ }}
+ .content {{
+ padding: 32px 40px;
+ }}
+ .greeting {{
+ font-size: 16px;
+ margin-bottom: 20px;
+ color: #333333;
+ }}
+ .message {{
+ font-size: 16px;
+ color: #333333;
+ margin-bottom: 20px;
+ }}
+ .key-container {{
+ margin: 28px 0;
+ }}
+ .key-label {{
+ font-size: 14px;
+ font-weight: 500;
+ margin-bottom: 8px;
+ color: #4b5563;
+ }}
+ .key {{
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
+ word-break: break-all;
+ background-color: #f9fafb;
+ border-radius: 6px;
+ padding: 16px;
+ font-size: 14px;
+ border: 1px solid #e5e7eb;
+ color: #4338ca;
+ }}
+ h2 {{
+ font-size: 18px;
+ font-weight: 600;
+ margin-top: 36px;
+ margin-bottom: 16px;
+ color: #333333;
+ }}
+ .budget-info {{
+ background-color: #f0fdf4;
+ border-radius: 6px;
+ padding: 14px 16px;
+ margin: 24px 0;
+ font-size: 14px;
+ border: 1px solid #dcfce7;
+ }}
+ .code-block {{
+ background-color: #f8fafc;
+ color: #334155;
+ border-radius: 8px;
+ padding: 20px;
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
+ font-size: 13px;
+ overflow-x: auto;
+ margin: 20px 0;
+ line-height: 1.6;
+ border: 1px solid #e2e8f0;
+ }}
+ .code-comment {{
+ color: #64748b;
+ }}
+ .code-string {{
+ color: #0369a1;
+ }}
+ .code-keyword {{
+ color: #7e22ce;
+ }}
+ .btn {{
+ display: inline-block;
+ padding: 8px 20px;
+ background-color: #6366f1;
+ color: #ffffff !important;
+ text-decoration: none;
+ border-radius: 6px;
+ font-weight: 500;
+ margin-top: 24px;
+ text-align: center;
+ font-size: 14px;
+ transition: background-color 0.2s;
+ }}
+ .btn:hover {{
+ background-color: #4f46e5;
+ color: #ffffff !important;
+ }}
+ .separator {{
+ height: 1px;
+ background-color: #f1f5f9;
+ margin: 40px 0 30px;
+ }}
+ .footer {{
+ padding: 24px 40px 32px;
+ text-align: center;
+ color: #64748b;
+ font-size: 13px;
+ background-color: #f8fafc;
+ border-top: 1px solid #f1f5f9;
+ }}
+ .social-links {{
+ margin-top: 12px;
+ }}
+ .social-links a {{
+ display: inline-block;
+ margin: 0 8px;
+ color: #64748b;
+ text-decoration: none;
+ }}
+ @media only screen and (max-width: 620px) {{
+ .container {{
+ width: 100%;
+ margin: 0;
+ border-radius: 0;
+ }}
+ .content {{
+ padding: 24px 20px;
+ }}
+ .footer {{
+ padding: 20px;
+ }}
+ }}
+ </style>
+</head>
+<body>
+ <div class="container">
+ <div class="header">
+ <img src="{email_logo_url}" alt="LiteLLM Logo" style="height: 32px; width: auto;">
+ </div>
+ <div class="content">
+ <div class="greeting">
+ <p>Hi {recipient_email},</p>
+ </div>
+
+ <div class="message">
+ <p>Great news! Your LiteLLM API key is ready to use.</p>
+ </div>
+
+ <div class="budget-info">
+ <p style="margin: 0;"><strong>Monthly Budget:</strong> {key_budget}</p>
+ </div>
+
+ <div class="key-container">
+ <div class="key-label">Your API Key</div>
+ <div class="key">{key_token}</div>
+ </div>
+
+ <h2>Quick Start Guide</h2>
+ <p>Here's how to use your key with the OpenAI SDK:</p>
+
+ <div class="code-block">
+<span class="code-keyword">import</span> openai<br>
+<br>
+client = openai.OpenAI(<br>
+&nbsp;&nbsp;api_key=<span class="code-string">"{key_token}"</span>,<br>
+&nbsp;&nbsp;base_url=<span class="code-string">"{base_url}"</span><br>
+)<br>
+<br>
+response = client.chat.completions.create(<br>
+&nbsp;&nbsp;model=<span class="code-string">"gpt-3.5-turbo"</span>, <span class="code-comment"># model to send to the proxy</span><br>
+&nbsp;&nbsp;messages = [<br>
+&nbsp;&nbsp;&nbsp;&nbsp;{{<br>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="code-string">"role"</span>: <span class="code-string">"user"</span>,<br>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="code-string">"content"</span>: <span class="code-string">"this is a test request, write a short poem"</span><br>
+&nbsp;&nbsp;&nbsp;&nbsp;}}<br>
+&nbsp;&nbsp;]<br>
+)
+ </div>
+
+ <a href="https://docs.litellm.ai/docs/proxy/user_keys" class="btn" style="color: #ffffff;">View Documentation</a>
+
+ <div class="separator"></div>
+
+ <h2>Need Help?</h2>
+ <p>If you have any questions or need assistance, please contact us at {email_support_contact}.</p>
+ </div>
+ <div class="footer">
+ <p>© 2023 LiteLLM. All rights reserved.</p>
+ <div class="social-links">
+ <a href="https://twitter.com/litellm">Twitter</a> •
+ <a href="https://github.com/BerriAI/litellm">GitHub</a> •
+ <a href="https://litellm.ai">Website</a>
+ </div>
+ </div>
+ </div>
+</body>
+</html>
+"""
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index 09b9817d603..89702e0345f 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -135,11 +135,15 @@ from .specialty_caches.dynamic_logging_cache import DynamicLoggingCache
try:
from enterprise.enterprise_callbacks.generic_api_callback import GenericAPILogger
+ from enterprise.enterprise_callbacks.send_emails.resend_email import (
+ ResendEmailLogger,
+ )
except Exception as e:
verbose_logger.debug(
f"[Non-Blocking] Unable to import GenericAPILogger - LiteLLM Enterprise Feature - {str(e)}"
)
GenericAPILogger = CustomLogger # type: ignore
+ ResendEmailLogger = CustomLogger # type: ignore
_in_memory_loggers: List[Any] = []
@@ -3040,6 +3044,13 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915
generic_api_logger = GenericAPILogger()
_in_memory_loggers.append(generic_api_logger)
return generic_api_logger # type: ignore
+ elif logging_integration == "resend_email":
+ for callback in _in_memory_loggers:
+ if isinstance(callback, ResendEmailLogger):
+ return callback
+ resend_email_logger = ResendEmailLogger()
+ _in_memory_loggers.append(resend_email_logger)
+ return resend_email_logger # type: ignore
elif logging_integration == "humanloop":
for callback in _in_memory_loggers:
if isinstance(callback, HumanloopLogger):
@@ -3187,6 +3198,10 @@ def get_custom_logger_compatible_class( # noqa: PLR0915
for callback in _in_memory_loggers:
if isinstance(callback, GenericAPILogger):
return callback
+ elif logging_integration == "resend_email":
+ for callback in _in_memory_loggers:
+ if isinstance(callback, ResendEmailLogger):
+ return callback
return None
except Exception as e:
diff --git a/litellm/litellm_core_utils/logging_callback_manager.py b/litellm/litellm_core_utils/logging_callback_manager.py
index c57a2401b7b..dec3add4e1b 100644
--- a/litellm/litellm_core_utils/logging_callback_manager.py
+++ b/litellm/litellm_core_utils/logging_callback_manager.py
@@ -260,4 +260,9 @@ class LoggingCallbackManager:
"""
Get all custom loggers that are instances of the given class type
"""
- return [c for c in self._get_all_callbacks() if isinstance(c, callback_type)]
+ # ensure we don't have duplicate instances
+ all_callbacks = []
+ for callback in self._get_all_callbacks():
+ if isinstance(callback, callback_type) and callback not in all_callbacks:
+ all_callbacks.append(callback)
+ return all_callbacks
diff --git a/litellm/proxy/hooks/key_management_event_hooks.py b/litellm/proxy/hooks/key_management_event_hooks.py
index cd5b1f353b7..047dd976925 100644
--- a/litellm/proxy/hooks/key_management_event_hooks.py
+++ b/litellm/proxy/hooks/key_management_event_hooks.py
@@ -21,7 +21,6 @@ from litellm.proxy._types import (
RegenerateKeyRequest,
UpdateKeyRequest,
UserAPIKeyAuth,
- WebhookEvent,
)
# NOTE: This is the prefix for all virtual keys stored in AWS Secrets Manager
@@ -298,13 +297,16 @@ class KeyManagementEventHooks:
@staticmethod
async def _send_key_created_email(response: dict):
+ from enterprise.enterprise_callbacks.send_emails.base_email import (
+ BaseEmailLogger,
+ )
from litellm.proxy.proxy_server import general_settings, proxy_logging_obj
+ from litellm.types.enterprise.enterprise_callbacks.send_emails import (
+ SendKeyCreatedEmailEvent,
+ )
- if "email" not in general_settings.get("alerting", []):
- raise ValueError(
- "Email alerting not setup on config.yaml. Please set `alerting=['email']. \nDocs: https://docs.litellm.ai/docs/proxy/email`"
- )
- event = WebhookEvent(
+ event = SendKeyCreatedEmailEvent(
+ virtual_key=response.get("key", ""),
event="key_created",
event_group=Litellm_EntityType.KEY,
event_message="API Key Created",
@@ -316,9 +318,33 @@ class KeyManagementEventHooks:
key_alias=response.get("key_alias", None),
)
- # If user configured email alerting - send an Email letting their end-user know the key was created
- asyncio.create_task(
- proxy_logging_obj.slack_alerting_instance.send_key_created_or_user_invited_email(
- webhook_event=event,
+ ##########################
+ # v2 integration for emails
+ ##########################
+ initialized_email_loggers = (
+ litellm.logging_callback_manager.get_custom_loggers_for_type(
+ callback_type=BaseEmailLogger
)
)
+ if len(initialized_email_loggers) > 0:
+ for email_logger in initialized_email_loggers:
+ if isinstance(email_logger, BaseEmailLogger):
+ await email_logger.send_key_created_email(
+ send_key_created_email_event=event,
+ )
+
+ ##########################
+ # v0 integration for emails
+ ##########################
+ else:
+ if "email" not in general_settings.get("alerting", []):
+ raise ValueError(
+ "Email alerting not setup on config.yaml. Please set `alerting=['email']. \nDocs: https://docs.litellm.ai/docs/proxy/email`"
+ )
+
+ # If user configured email alerting - send an Email letting their end-user know the key was created
+ asyncio.create_task(
+ proxy_logging_obj.slack_alerting_instance.send_key_created_or_user_invited_email(
+ webhook_event=event,
+ )
+ )
diff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yaml
index 1cfa97a656c..39e7cfd07a7 100644
--- a/litellm/proxy/proxy_config.yaml
+++ b/litellm/proxy/proxy_config.yaml
@@ -6,4 +6,4 @@ model_list:
litellm_settings:
- json_logs: true
\ No newline at end of file
+ callbacks: ["resend_email"]
\ No newline at end of file
diff --git a/litellm/types/enterprise/enterprise_callbacks/send_emails.py b/litellm/types/enterprise/enterprise_callbacks/send_emails.py
new file mode 100644
index 00000000000..634bb444c4b
--- /dev/null
+++ b/litellm/types/enterprise/enterprise_callbacks/send_emails.py
@@ -0,0 +1,10 @@
+from litellm.proxy._types import WebhookEvent
+
+
+class SendKeyCreatedEmailEvent(WebhookEvent):
+ virtual_key: str
+ """
+ The virtual key that was created
+
+ this will be sk-123xxx, since we will be emailing this to the user to start using the key
+ """
diff --git a/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_base_email.py b/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_base_email.py
new file mode 100644
index 00000000000..ccc596de148
--- /dev/null
+++ b/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_base_email.py
@@ -0,0 +1,104 @@
+import json
+import os
+import sys
+import unittest.mock as mock
+
+import pytest
+from fastapi.testclient import TestClient
+
+sys.path.insert(0, os.path.abspath("../../.."))
+
+from enterprise.enterprise_callbacks.send_emails.base_email import BaseEmailLogger
+from litellm.proxy._types import Litellm_EntityType
+from litellm.types.enterprise.enterprise_callbacks.send_emails import (
+ SendKeyCreatedEmailEvent,
+)
+
+
+def base_email_logger():
+ return BaseEmailLogger()
+
+
+def mock_send_email():
+ with mock.patch.object(BaseEmailLogger, "send_email") as mock_send:
+ yield mock_send
+
+
+def mock_lookup_user_email():
+ with mock.patch.object(
+ BaseEmailLogger, "_lookup_user_email_from_db"
+ ) as mock_lookup:
+ yield mock_lookup
+
+
+def test_format_key_budget(base_email_logger):
+ # Test with budget
+ assert base_email_logger._format_key_budget(100.0) == "$100.0"
+
+ # Test with no budget
+ assert base_email_logger._format_key_budget(None) == "No budget"
+
+
+async def test_send_key_created_email(
+ base_email_logger, mock_send_email, mock_lookup_user_email
+):
+ # Setup test data
+ event = SendKeyCreatedEmailEvent(
+ user_id="test_user",
+ user_email="[email protected]",
+ virtual_key="test_key",
+ max_budget=100.0,
+ spend=0.0,
+ event_group=Litellm_EntityType.USER,
+ event="key_created",
+ event_message="Test Key Created",
+ )
+
+ # Mock environment variables
+ with mock.patch.dict(
+ os.environ,
+ {
+ "EMAIL_LOGO_URL": "https://test-logo.com",
+ "EMAIL_SUPPORT_CONTACT": "[email protected]",
+ "PROXY_BASE_URL": "http://test.com",
+ },
+ ):
+ # Execute
+ await base_email_logger.send_key_created_email(event)
+
+ # Verify
+ mock_send_email.assert_called_once()
+ call_args = mock_send_email.call_args[1]
+ assert call_args["from_email"] == BaseEmailLogger.DEFAULT_LITELLM_EMAIL
+ assert call_args["to_email"] == ["[email protected]"]
+ assert call_args["subject"] == "LiteLLM: Test Key Created"
+ assert "test_key" in call_args["html_body"]
+ assert "$100.0" in call_args["html_body"]
+
+
+async def test_send_key_created_email_no_email(
+ base_email_logger, mock_lookup_user_email
+):
+ # Setup test data with no email
+ event = SendKeyCreatedEmailEvent(
+ user_id="test_user",
+ user_email=None,
+ virtual_key="test_key",
+ max_budget=100.0,
+ event_message="Test Key Created",
+ event_group=Litellm_EntityType.USER,
+ event="key_created",
+ spend=0.0,
+ )
+
+ # Mock lookup to return None
+ mock_lookup_user_email.return_value = None
+
+ # Test that it raises ValueError
+ with pytest.raises(ValueError, match="User email not found"):
+ await base_email_logger.send_key_created_email(event)
diff --git a/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_resend_email.py b/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_resend_email.py
new file mode 100644
index 00000000000..980fd49b948
--- /dev/null
+++ b/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_resend_email.py
@@ -0,0 +1,117 @@
+import os
+import sys
+import unittest.mock as mock
+
+import pytest
+from httpx import Response
+
+sys.path.insert(0, os.path.abspath("../../.."))
+
+from enterprise.enterprise_callbacks.send_emails.resend_email import ResendEmailLogger
+
+
+def mock_env_vars():
+ with mock.patch.dict(os.environ, {"RESEND_API_KEY": "test_api_key"}):
+ yield
+
+
+def mock_httpx_client():
+ with mock.patch(
+ "enterprise.enterprise_callbacks.send_emails.resend_email.get_async_httpx_client"
+ ) as mock_client:
+ # Create a mock response
+ mock_response = mock.AsyncMock(spec=Response)
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"id": "test_email_id"}
+
+ # Create a mock client
+ mock_async_client = mock.AsyncMock()
+ mock_async_client.post.return_value = mock_response
+ mock_client.return_value = mock_async_client
+
+ yield mock_async_client
+
+
+async def test_send_email_success(mock_env_vars, mock_httpx_client):
+ # Initialize the logger
+ logger = ResendEmailLogger()
+
+ # Test data
+ from_email = "[email protected]"
+ to_email = ["[email protected]"]
+ subject = "Test Subject"
+ html_body = "<p>Test email body</p>"
+
+ # Send email
+ await logger.send_email(
+ from_email=from_email, to_email=to_email, subject=subject, html_body=html_body
+ )
+
+ # Verify the HTTP client was called correctly
+ mock_httpx_client.post.assert_called_once()
+ call_args = mock_httpx_client.post.call_args
+
+ # Verify the URL
+ assert call_args[1]["url"] == "https://api.resend.com/emails"
+
+ # Verify the request body
+ request_body = call_args[1]["json"]
+ assert request_body["from"] == from_email
+ assert request_body["to"] == to_email
+ assert request_body["subject"] == subject
+ assert request_body["html"] == html_body
+
+ # Verify the headers
+ assert call_args[1]["headers"] == {"Authorization": "Bearer test_api_key"}
+
+
+async def test_send_email_missing_api_key(mock_httpx_client):
+ # Remove the API key from environment
+ if "RESEND_API_KEY" in os.environ:
+ del os.environ["RESEND_API_KEY"]
+
+ # Initialize the logger
+ logger = ResendEmailLogger()
+
+ # Test data
+ from_email = "[email protected]"
+ to_email = ["[email protected]"]
+ subject = "Test Subject"
+ html_body = "<p>Test email body</p>"
+
+ # Send email
+ await logger.send_email(
+ from_email=from_email, to_email=to_email, subject=subject, html_body=html_body
+ )
+
+ # Verify the HTTP client was called with None as the API key
+ mock_httpx_client.post.assert_called_once()
+ call_args = mock_httpx_client.post.call_args
+ assert call_args[1]["headers"] == {"Authorization": "Bearer None"}
+
+
+async def test_send_email_multiple_recipients(mock_env_vars, mock_httpx_client):
+ # Initialize the logger
+ logger = ResendEmailLogger()
+
+ # Test data with multiple recipients
+ from_email = "[email protected]"
+ subject = "Test Subject"
+ html_body = "<p>Test email body</p>"
+
+ # Send email
+ await logger.send_email(
+ from_email=from_email, to_email=to_email, subject=subject, html_body=html_body
+ )
+
+ # Verify the HTTP client was called with multiple recipients
+ mock_httpx_client.post.assert_called_once()
+ call_args = mock_httpx_client.post.call_args
+ request_body = call_args[1]["json"]
+ assert request_body["to"] == to_email
diff --git a/tests/logging_callback_tests/test_unit_tests_init_callbacks.py b/tests/logging_callback_tests/test_unit_tests_init_callbacks.py
index 5aa97304cb7..f6edf71498f 100644
--- a/tests/logging_callback_tests/test_unit_tests_init_callbacks.py
+++ b/tests/logging_callback_tests/test_unit_tests_init_callbacks.py
@@ -43,6 +43,7 @@ from litellm.integrations.agentops import AgentOps
from litellm.integrations.humanloop import HumanloopLogger
from litellm.proxy.hooks.dynamic_rate_limiter import _PROXY_DynamicRateLimitHandler
from enterprise.enterprise_callbacks.generic_api_callback import GenericAPILogger
+from enterprise.enterprise_callbacks.send_emails.resend_email import ResendEmailLogger
from unittest.mock import patch
# clear prometheus collectors / registry
@@ -81,6 +82,7 @@ callback_class_str_to_classType = {
"agentops": AgentOps,
"bedrock_vector_store": BedrockVectorStore,
"generic_api": GenericAPILogger,
+ "resend_email": ResendEmailLogger,
}
expected_env_vars = {