email.py
Overview
The email.py file provides a reusable email sending component designed for integration within the InfiniFlow system. It encapsulates the functionality to compose and send emails via SMTP, supporting multiple recipients, CC, HTML content, and error handling with retry logic. This component abstracts the complexity of SMTP interactions and exposes a parameterized interface for sending emails programmatically.
Key features include:
Definition of email parameters (recipient, CC, subject, content).
Support for SMTP authentication and secure connection (STARTTLS).
Retry mechanism for transient SMTP errors.
Logging of connection, authentication, and sending processes.
Graceful handling of errors with informative output.
Timeout enforcement on execution to prevent hanging.
This component is intended to be used where programmatic email notifications or communications are needed, such as alerting, reporting, or user messaging within the InfiniFlow platform.
Classes and Methods
EmailParam (ToolParamBase)
Defines configuration and runtime parameters for the Email component.
Attributes
meta: ToolMeta
Metadata describing the component, including name, description, and parameter schema.smtp_server: str
SMTP server address (e.g.,smtp.gmail.com).smtp_port: int
SMTP server port (default 465).email: str
Sender's email address.password: str
Authorization code or password for the sender email account.sender_name: str
Display name of the email sender.
Methods
init()
Initializes default metadata and parameters. Sets fixed configuration placeholders for SMTP server, port, sender email, password, and sender name.check()
Validates that all required SMTP connection parameters (smtp_server,email,password,sender_name) are non-empty. Raises exceptions if validation fails.get_input_form() -> dict[str, dict]
Returns a dictionary describing the user input form fields:to_email(required): Recipient email address.subject(optional): Email subject line.cc_email(optional): Carbon copy recipients, comma-separated.
Usage Example
param = EmailParam()
param.smtp_server = "smtp.gmail.com"
param.smtp_port = 587
param.email = "[email protected]"
param.password = "authcode"
param.sender_name = "InfiniFlow Bot"
param.check() # Validates parameters
Email (ToolBase, ABC)
Primary class for sending emails. Implements the core logic for composing and sending email messages via an SMTP server.
Class Attributes
component_name: str = "Email"
Identifier for the component.
Methods
_invoke(self, **kwargs)
Main method to send an email. Decorated with a timeout to limit execution time (default 60 seconds or environment configured).Parameters:
to_email(str): Recipient email address (required).cc_email(str): Optional CC recipients, comma-separated.subject(str): Optional email subject.content(str): Optional email content (HTML format by default).
Returns:
Trueif email was sent successfully.Falseif sending failed.
Behavior:
Validates required fields.
Constructs an email message with proper encoding and MIME multipart support.
Connects to the SMTP server securely using STARTTLS.
Authenticates using stored sender credentials.
Attempts to send the email, using
send_messageprimarily and falling back tosendmailon failure.Implements retry on SMTP connection errors or failures, respecting configured retry counts and delays.
Logs each step and errors.
Sets component output flags indicating success or error status.
thoughts(self) -> str
Generates a user-friendly confirmation message indicating that the email is being sent. Uses current inputs forto_emailandsubject.Returns:
A formatted string summary.
Implementation Details and Algorithms
Retry Logic:
The_invokemethod attempts to send the email multiple times (max_retries + 1) if SMTP connection errors occur, with a sleep delay specified by_param.delay_after_error. This provides resilience against transient network or server issues.SMTP Connection:
Uses Python'ssmtplibto connect to the SMTP server. Starts with a secure context and upgrades the connection to TLS withstarttls().Email Composition:
Usesemail.mimeclasses to build a MIME multipart email supporting HTML content. Sender name and subject are encoded in UTF-8 to support international characters.Error Handling:
Differentiates between JSON decode errors, SMTP authentication errors, connection errors, general SMTP exceptions, and unexpected exceptions. Each error sets an appropriate output error message and logs details.Timeout Enforcement:
The@timeoutdecorator ensures the method does not run indefinitely, preventing system resource exhaustion.
Usage Example
email_tool = Email()
email_tool._param = EmailParam()
email_tool._param.smtp_server = "smtp.gmail.com"
email_tool._param.smtp_port = 587
email_tool._param.email = "[email protected]"
email_tool._param.password = "authcode"
email_tool._param.sender_name = "InfiniFlow Bot"
email_tool._param.max_retries = 3
email_tool._param.delay_after_error = 5
result = email_tool._invoke(
to_email="[email protected]",
cc_email="[email protected],[email protected]",
subject="Hello from InfiniFlow",
content="<h1>Test Email</h1><p>This is a test message.</p>"
)
if result:
print("Email sent successfully")
else:
print("Failed to send email")
Interaction with Other System Components
agent.tools.base
Inherits fromToolBase,ToolParamBase, and usesToolMetafor standardized tool parameterization and metadata management.api.utils.api_utils.timeout
Uses a timeout decorator to enforce execution time limits and avoid long-running or stuck processes.The component is designed to be integrated into an agent or workflow system that passes parameters dynamically, such as the recipient address, subject, and content, and expects structured output indicating success or failure.
Important Implementation Notes
The SMTP connection uses
starttls()rather than implicit SSL on port 465, despite the default port being set to 465. This may require port adjustment depending on the SMTP server configuration.The sender's display name is encoded using
email.header.Headerand combined with the email address usingformataddrto ensure proper formatting.The email content is sent as HTML (
MIMETextwith subtype'html'), enabling rich formatting.The retry mechanism catches specific SMTP exceptions and retries sending after a delay, improving reliability in unstable network conditions.
The
_invokemethod logs all significant steps, aiding in debugging and audit trails.
Mermaid Class Diagram
classDiagram
class EmailParam {
+meta: ToolMeta
+smtp_server: str
+smtp_port: int
+email: str
+password: str
+sender_name: str
+__init__()
+check()
+get_input_form() dict
}
class Email {
+component_name: str
+_invoke(kwargs) bool
+thoughts() str
}
ToolParamBase <|-- EmailParam
ToolBase <|-- Email
Email ..|> ABC
Summary
The email.py file defines a robust, configurable email sending tool for the InfiniFlow system. It cleanly separates parameter definition (EmailParam) from execution logic (Email), enabling easy integration and reuse. The component handles essential email sending features, including multiple recipients, CC, HTML content, and SMTP authentication, with resilience to errors through retries and detailed logging.
This modular design allows the email tool to be a foundational building block for automated communications within workflows or agents relying on the InfiniFlow platform.