Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

feat: Integrate Resend to Camel (#3096)

Ol1ver041353e0d8dcb1f0
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.py
index 214188ee0..3ce811023 100644
--- a/camel/toolkits/__init__.py
+++ b/camel/toolkits/__init__.py
@@ -76,6 +76,7 @@ from .klavis_toolkit import KlavisToolkit
from .aci_toolkit import ACIToolkit
from .origene_mcp_toolkit import OrigeneToolkit
from .playwright_mcp_toolkit import PlaywrightMCPToolkit
+from .resend_toolkit import ResendToolkit
from .wolfram_alpha_toolkit import WolframAlphaToolkit
from .task_planning_toolkit import TaskPlanningToolkit
from .hybrid_browser_toolkit import HybridBrowserToolkit
@@ -155,6 +156,7 @@ __all__ = [
'KlavisToolkit',
'ACIToolkit',
'PlaywrightMCPToolkit',
+ 'ResendToolkit',
'WolframAlphaToolkit',
'BohriumToolkit',
'OpenAIImageToolkit', # Backward compatibility
diff --git a/camel/toolkits/resend_toolkit.py b/camel/toolkits/resend_toolkit.py
new file mode 100644
index 000000000..33b5e52a0
--- /dev/null
+++ b/camel/toolkits/resend_toolkit.py
@@ -0,0 +1,168 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+
+from typing import Dict, List, Optional, cast
+
+from camel.toolkits.base import BaseToolkit
+from camel.toolkits.function_tool import FunctionTool
+from camel.utils import MCPServer, api_keys_required
+
+
+@MCPServer()
+class ResendToolkit(BaseToolkit):
+ r"""A toolkit for sending emails using the Resend API.
+
+ This toolkit provides functionality to send emails using Resend's
+ Python SDK.It supports sending both HTML and plain text emails,
+ with options for multiple recipients, CC, BCC, reply-to
+ addresses, and custom headers.
+
+ Notes:
+ To use this toolkit, you need to set the following environment
+ variable:
+ - RESEND_API_KEY: Your Resend API key. You can get one from
+ https://resend.com/api-keys
+
+ Example:
+ .. code-block:: python
+
+ from camel.toolkits import ResendToolkit
+
+ # Initialize the toolkit
+ toolkit = ResendToolkit()
+
+ # Get tools
+ tools = toolkit.get_tools()
+ """
+
+ @api_keys_required([(None, "RESEND_API_KEY")])
+ def send_email(
+ self,
+ to: List[str],
+ subject: str,
+ from_email: str,
+ html: Optional[str] = None,
+ text: Optional[str] = None,
+ cc: Optional[List[str]] = None,
+ bcc: Optional[List[str]] = None,
+ reply_to: Optional[str] = None,
+ tags: Optional[List[Dict[str, str]]] = None,
+ headers: Optional[Dict[str, str]] = None,
+ ) -> str:
+ r"""Send an email using the Resend API.
+
+ Args:
+ to (List[str]): List of recipient email addresses.
+ subject (str): The email subject line.
+ from_email (str): The sender email address. Must be from a verified
+ domain.
+ html (Optional[str]): The HTML content of the email. Either html or
+ text must be provided. (default: :obj:`None`)
+ text (Optional[str]): The plain text content of the email. Either
+ html or text must be provided. (default: :obj:`None`)
+ cc (Optional[List[str]]): List of CC recipient email addresses.
+ (default: :obj:`None`)
+ bcc (Optional[List[str]]): List of BCC recipient email addresses.
+ (default: :obj:`None`)
+ reply_to (Optional[str]): The reply-to email address.
+ (default: :obj:`None`)
+ tags (Optional[List[Dict[str, str]]]): List of tags to attach to
+ the email. Each tag should be a dict with 'name' and
+ 'value' keys. (default: :obj:`None`)
+ headers (Optional[Dict[str, str]]): Custom headers to include in
+ the email.(default: :obj:`None`)
+
+ Returns:
+ str: A success message with the email ID if sent successfully,
+ or an error message if the send failed.
+
+ Raises:
+ ValueError: If neither html nor text content is provided.
+
+ Example:
+ .. code-block:: python
+
+ toolkit = ResendToolkit()
+ result = toolkit.send_email(
+ subject="Hello World",
+ from_email="[email protected]",
+ html="<h1>Hello, World!</h1>",
+ text="Hello, World!"
+ )
+ """
+ import os
+
+ if not html and not text:
+ raise ValueError(
+ "Either 'html' or 'text' content must be provided"
+ )
+
+ try:
+ import resend
+ except ImportError:
+ raise ImportError(
+ "Please install the resend package first. "
+ "You can install it by running `pip install resend`."
+ )
+
+ # Set the API key
+ resend.api_key = os.getenv("RESEND_API_KEY")
+
+ # Prepare email parameters
+ params: resend.Emails.SendParams = {
+ "from": from_email,
+ "to": to,
+ "subject": subject,
+ }
+
+ # Add content
+ if html:
+ params["html"] = html
+ if text:
+ params["text"] = text
+
+ # Add optional parameters
+ if cc:
+ params["cc"] = cc
+ if bcc:
+ params["bcc"] = bcc
+ if reply_to:
+ params["reply_to"] = reply_to
+ if tags:
+ params["tags"] = cast('list[resend.emails._tag.Tag]', tags)
+ if headers:
+ params["headers"] = headers
+
+ try:
+ # Send the email
+ email = resend.Emails.send(params)
+ return (
+ f"Email sent successfully. "
+ f"Email ID: {email.get('id', 'Unknown')}"
+ )
+ except Exception as e:
+ return f"Failed to send email: {e!s}"
+
+ def get_tools(self) -> List[FunctionTool]:
+ r"""Returns a list of FunctionTool objects representing the
+ functions in the toolkit.
+
+ Returns:
+ List[FunctionTool]: A list of FunctionTool objects
+ representing the functions in the toolkit.
+ """
+ return [
+ FunctionTool(self.send_email),
+ ]
diff --git a/examples/toolkits/resend_toolkit.py b/examples/toolkits/resend_toolkit.py
new file mode 100644
index 000000000..7055710b2
--- /dev/null
+++ b/examples/toolkits/resend_toolkit.py
@@ -0,0 +1,115 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+from camel.agents import ChatAgent
+from camel.models import ModelFactory
+from camel.toolkits import ResendToolkit
+from camel.types import ModelPlatformType, ModelType
+
+
+def main():
+ # Initialize ResendToolkit
+ resend_toolkit = ResendToolkit()
+
+ # Create model
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.DEFAULT,
+ model_type=ModelType.DEFAULT,
+ )
+
+ # Create agent with ResendToolkit
+ agent = ChatAgent(
+ system_message="You are an email assistant. "
+ "Help send emails using the ResendToolkit.The sender email is "
+ model=model,
+ tools=resend_toolkit.get_tools(),
+ )
+
+ # Example 1: Send a simple HTML email
+ print("=" * 50)
+ print("Example 1: HTML Email")
+ print("=" * 50)
+ response = agent.step(
+ "Send an email to [email protected] with subject 'Welcome to CAMEL AI' "
+ "and HTML content '<h1>Welcome!</h1><p>Thank you for joining "
+ "CAMEL AI.</p>' from [email protected]"
+ )
+ print(response.msg.content)
+
+ # Example 2: Send email with CC
+ print("\n" + "=" * 50)
+ print("Example 2: Email with CC")
+ print("=" * 50)
+ response = agent.step(
+ "Send an email to [email protected] with CC to [email protected] "
+ "with subject 'CAMEL AI Test Email' and text content "
+ "'This is a test email from CAMEL AI ResendToolkit.' "
+ )
+ print(response.msg.content)
+
+ # Example 3: Send email with both HTML and text content
+ print("\n" + "=" * 50)
+ print("Example 3: Newsletter Email")
+ print("=" * 50)
+ response = agent.step(
+ "Send an email to [email protected] with subject 'Weekly Newsletter' "
+ "from [email protected] with HTML content "
+ "'<h2>Newsletter</h2><p>Here are this week updates.</p>' "
+ "and plain text content 'Newsletter\n\nHere are this week updates.'"
+ )
+ print(response.msg.content)
+
+
+if __name__ == "__main__":
+ main()
+
+"""
+==================================================
+Example 1: HTML Email
+==================================================
+Your email has been sent successfully.
+
+Details:
+- Subject: Welcome to CAMEL AI
+- Content type: HTML
+- Email ID: 92fd****b683
+
+==================================================
+Example 2: Email with CC
+==================================================
+Your email has been sent successfully.
+
+Details:
+- Subject: CAMEL AI Test Email
+- Content type: Text
+- Email ID: b0e3****0211
+
+==================================================
+Example 3: Newsletter Email
+==================================================
+Your email has been sent successfully.
+
+Details:
+- Subject: Weekly Newsletter
+- Content types: HTML and Plain Text
+- Email ID: 9bd0****86b1
+"""
diff --git a/pyproject.toml b/pyproject.toml
index 29c395d96..3f0ba3fa4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -147,6 +147,7 @@ communication_tools = [
"discord.py>=2.3.2,<3",
"notion-client>=2.2.1,<3",
"praw>=7.7.1,<8",
+ "resend>=2.0.0,<3",
]
data_tools = [
"numpy>=1.2,<=2.2",
@@ -344,6 +345,7 @@ all = [
"ipykernel>=6.0.0,<7",
"agentops>=0.3.21,<0.4",
"praw>=7.7.1,<8",
+ "resend>=2.0.0,<3",
"textblob>=0.17.1,<0.18",
"scholarly[tor]==1.7.11",
"notion-client>=2.2.1,<3",
@@ -597,6 +599,7 @@ module = [
"arxiv",
"arxiv2text",
"praw",
+ "resend",
"textblob",
"datacommons",
"datacommons_pandas",
diff --git a/test/toolkits/test_resend_toolkit.py b/test/toolkits/test_resend_toolkit.py
new file mode 100644
index 000000000..eb38d9312
--- /dev/null
+++ b/test/toolkits/test_resend_toolkit.py
@@ -0,0 +1,262 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+from unittest.mock import patch
+
+import pytest
+
+from camel.toolkits.resend_toolkit import ResendToolkit
+
+
[email protected](autouse=True)
+def set_env_vars(monkeypatch):
+ """Set up required environment variables for ResendToolkit tests."""
+ monkeypatch.setenv("RESEND_API_KEY", "re_test_api_key_12345")
+
+
+def test_send_email_html_only():
+ """Test sending email with HTML content only."""
+ toolkit = ResendToolkit()
+
+ mock_email_response = {'id': 'email_12345_test_id'}
+
+ with patch('resend.Emails.send') as mock_send:
+ mock_send.return_value = mock_email_response
+
+ result = toolkit.send_email(
+ subject="Test HTML Email",
+ from_email="[email protected]",
+ html="<h1>Hello, World!</h1><p>This is a test email.</p>",
+ )
+
+ expected_result = (
+ "Email sent successfully. Email ID: email_12345_test_id"
+ )
+ assert result == expected_result
+
+ # Verify the API was called with correct parameters
+ mock_send.assert_called_once()
+ call_args = mock_send.call_args[0][0]
+ assert call_args["from"] == "[email protected]"
+ assert call_args["to"] == ["[email protected]"]
+ assert call_args["subject"] == "Test HTML Email"
+ assert (
+ call_args["html"]
+ == "<h1>Hello, World!</h1><p>This is a test email.</p>"
+ )
+ assert "text" not in call_args
+
+
+def test_send_email_text_only():
+ """Test sending email with plain text content only."""
+ toolkit = ResendToolkit()
+
+ mock_email_response = {'id': 'email_text_67890_test_id'}
+
+ with patch('resend.Emails.send') as mock_send:
+ mock_send.return_value = mock_email_response
+
+ result = toolkit.send_email(
+ subject="Test Text Email",
+ from_email="[email protected]",
+ text="Hello, World!\nThis is a plain text test email.",
+ )
+
+ expected_result = (
+ "Email sent successfully. Email ID: email_text_67890_test_id"
+ )
+ assert result == expected_result
+
+ # Verify the API was called with correct parameters
+ mock_send.assert_called_once()
+ call_args = mock_send.call_args[0][0]
+ assert call_args["from"] == "[email protected]"
+ assert call_args["to"] == ["[email protected]"]
+ assert call_args["subject"] == "Test Text Email"
+ assert (
+ call_args["text"]
+ == "Hello, World!\nThis is a plain text test email."
+ )
+ assert "html" not in call_args
+
+
+def test_send_email_html_and_text():
+ """Test sending email with both HTML and text content."""
+ toolkit = ResendToolkit()
+
+ mock_email_response = {'id': 'email_both_11111_test_id'}
+
+ with patch('resend.Emails.send') as mock_send:
+ mock_send.return_value = mock_email_response
+
+ result = toolkit.send_email(
+ subject="Test Both Content Email",
+ from_email="[email protected]",
+ html="<h1>Hello, World!</h1>",
+ text="Hello, World!",
+ )
+
+ expected_result = (
+ "Email sent successfully. Email ID: email_both_11111_test_id"
+ )
+ assert result == expected_result
+
+ # Verify the API was called with correct parameters
+ mock_send.assert_called_once()
+ call_args = mock_send.call_args[0][0]
+ assert call_args["html"] == "<h1>Hello, World!</h1>"
+ assert call_args["text"] == "Hello, World!"
+
+
+def test_send_email_with_all_optional_params():
+ """Test sending email with all optional parameters."""
+ toolkit = ResendToolkit()
+
+ mock_email_response = {'id': 'email_full_22222_test_id'}
+
+ with patch('resend.Emails.send') as mock_send:
+ mock_send.return_value = mock_email_response
+
+ result = toolkit.send_email(
+ subject="Test Full Email",
+ from_email="[email protected]",
+ html="<h1>Full Email Test</h1>",
+ text="Full Email Test",
+ reply_to="[email protected]",
+ tags=[{"name": "category", "value": "test"}],
+ headers={"X-Custom-Header": "test-value"},
+ )
+
+ expected_result = (
+ "Email sent successfully. Email ID: email_full_22222_test_id"
+ )
+ assert result == expected_result
+
+ # Verify the API was called with correct parameters
+ mock_send.assert_called_once()
+ call_args = mock_send.call_args[0][0]
+ assert call_args["to"] == [
+ ]
+ assert call_args["cc"] == ["[email protected]"]
+ assert call_args["bcc"] == ["[email protected]"]
+ assert call_args["reply_to"] == "[email protected]"
+ assert call_args["tags"] == [{"name": "category", "value": "test"}]
+ assert call_args["headers"] == {"X-Custom-Header": "test-value"}
+
+
+def test_send_email_no_content_error():
+ """Test that sending email without content raises ValueError."""
+ toolkit = ResendToolkit()
+
+ with pytest.raises(
+ ValueError, match="Either 'html' or 'text' content must be provided"
+ ):
+ toolkit.send_email(
+ subject="Test Email",
+ from_email="[email protected]",
+ )
+
+
+def test_send_email_import_error():
+ """Test handling of resend package import error."""
+ toolkit = ResendToolkit()
+
+ # Mock the import statement inside the send_email method
+ with patch.dict('sys.modules', {'resend': None}):
+ with pytest.raises(
+ ImportError, match=r"Please install the resend package first\."
+ ):
+ toolkit.send_email(
+ subject="Test Email",
+ from_email="[email protected]",
+ text="Test content",
+ )
+
+
+def test_send_email_api_error():
+ """Test handling of API errors during email sending."""
+ toolkit = ResendToolkit()
+
+ with patch('resend.Emails.send') as mock_send:
+ mock_send.side_effect = Exception("API Error: Invalid API key")
+
+ result = toolkit.send_email(
+ subject="Test Email",
+ from_email="[email protected]",
+ text="Test content",
+ )
+
+ expected_result = "Failed to send email: API Error: Invalid API key"
+ assert result == expected_result
+
+
+def test_send_email_no_id_in_response():
+ """Test handling of API response without ID field."""
+ toolkit = ResendToolkit()
+
+ mock_email_response = {} # Response without 'id' field
+
+ with patch('resend.Emails.send') as mock_send:
+ mock_send.return_value = mock_email_response
+
+ result = toolkit.send_email(
+ subject="Test Email",
+ from_email="[email protected]",
+ text="Test content",
+ )
+
+ expected_result = "Email sent successfully. Email ID: Unknown"
+ assert result == expected_result
+
+
+def test_get_tools():
+ """Test that get_tools returns the correct FunctionTool objects."""
+ toolkit = ResendToolkit()
+ tools = toolkit.get_tools()
+
+ assert len(tools) == 1
+ assert tools[0].func == toolkit.send_email
+ assert hasattr(tools[0], 'get_openai_tool_schema')
+
+
+def test_send_email_api_key_setting():
+ """Test that the API key is correctly set from environment variable."""
+ toolkit = ResendToolkit()
+
+ with (
+ patch('resend.Emails.send') as mock_send,
+ patch('resend.api_key', new=None),
+ ):
+ mock_send.return_value = {'id': 'test_id'}
+
+ toolkit.send_email(
+ subject="Test Email",
+ from_email="[email protected]",
+ text="Test content",
+ )
+
+ # The API key should have been set during the function call
+ mock_send.assert_called_once()
diff --git a/uv.lock b/uv.lock
index 927753122..85af8a43d 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1,5 +1,5 @@
version = 1
-revision = 3
+revision = 2
requires-python = ">=3.10, <3.13"
resolution-markers = [
"python_full_version >= '3.12'",
@@ -763,6 +763,7 @@ all = [
{ name = "reka-api" },
{ name = "reportlab" },
{ name = "requests-oauthlib" },
+ { name = "resend" },
{ name = "rlcard" },
{ name = "rouge" },
{ name = "scenedetect" },
@@ -802,6 +803,7 @@ communication-tools = [
{ name = "praw" },
{ name = "pygithub" },
{ name = "pytelegrambotapi" },
+ { name = "resend" },
{ name = "slack-bolt" },
{ name = "slack-sdk" },
]
@@ -1332,6 +1334,8 @@ requires-dist = [
{ name = "requests-oauthlib", marker = "extra == 'eigent'", specifier = ">=1.3.1,<2" },
{ name = "requests-oauthlib", marker = "extra == 'owl'", specifier = ">=1.3.1,<2" },
{ name = "requests-oauthlib", marker = "extra == 'web-tools'", specifier = ">=1.3.1,<2" },
+ { name = "resend", marker = "extra == 'all'", specifier = ">=2.0.0,<3" },
+ { name = "resend", marker = "extra == 'communication-tools'", specifier = ">=2.0.0,<3" },
{ name = "rlcard", marker = "extra == 'all'", specifier = ">=1.0.0,<1.3.0" },
{ name = "rouge", marker = "extra == 'all'", specifier = ">=1.0.1,<2" },
{ name = "rouge", marker = "extra == 'data-tools'", specifier = ">=1.0.1,<2" },
@@ -6951,6 +6955,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/3f/51/d4db610ef29373b879047326cbf6fa98b6c1969d6f6dc423279de2b1be2c/requests_toolbelt-1.0.0-py2.py3-none-any.whl", hash = "sha256:cccfdd665f0a24fcf4726e690f65639d272bb0637b9b92dfd91a5568ccf6bd06", size = 54481, upload-time = "2023-05-01T04:11:28.427Z" },
]
+[[package]]
+name = "resend"
+version = "2.13.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "requests" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/d6/ba/de34669cd9ccf2efa65938691ae054e908cbb9c3f2f4cf5ec74d4bbc875e/resend-2.13.1.tar.gz", hash = "sha256:689e2abf17ec46acf97400c096869e95cbb0b67572b0132d1158fdbbf9b1deba", size = 15465, upload-time = "2025-08-26T15:06:47.295Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ab/6a/a5837efa1e8ff6d5c8a40574b506f85ce725126303cedec7c6e1b4382a03/resend-2.13.1-py2.py3-none-any.whl", hash = "sha256:4104d3c8f2c91113c7629e4d51ab1ca255272dd9355d2c584ab1fc10a8c65bee", size = 22279, upload-time = "2025-08-26T15:06:46.293Z" },
+]
+
[[package]]
name = "rfc3339-validator"
version = "0.1.4"