Skip to content

Email Main Class

Email(title='Email Report')

Main email class responsible for managing and rendering email content.

This class is the core of the EmailWidget library, used to create and manage HTML email reports. It serves as a powerful container that can add, manage, and orchestrate various "widgets", ultimately rendering them into a beautiful, professional HTML email.

Core features
  • Widget Management: Easily add, remove, find, and iterate through various content components (text, tables, charts, etc.).
  • Email Property Configuration: Customize email title, subtitle, and footer.
  • Convenience Methods: Provides a series of add_* methods for quickly creating and adding common widgets, simplifying code.
  • Content Export: Supports exporting emails as standalone HTML files or getting HTML string content.
  • Style Configuration: Through EmailConfig object, customize email theme colors, fonts, and layout width.

Attributes:

Name Type Description
title str

The main title of the email.

subtitle Optional[str]

The subtitle of the email, displayed below the main title.

footer_text Optional[str]

The footer text of the email.

widgets List[BaseWidget]

List storing all added widgets.

config EmailConfig

The email configuration object for controlling styles and behavior.

Examples:

A basic email creation and export workflow:

Python
from email_widget import Email
from email_widget.core.enums import TextType, AlertType

# 1. Create an email object
email = Email("Quarterly Sales Report")

# 2. Set email metadata
email.set_subtitle("Q1 2024")
email.set_footer("This report is generated by the sales analysis team")

# 3. Use convenience methods to add content
email.add_text("Executive Summary", text_type=TextType.TITLE_LARGE)
email.add_text("Total sales this quarter reached 1,234,567 yuan, a year-over-year growth of 15%.")
email.add_alert("Note: Data is still under preliminary verification.", alert_type=AlertType.WARNING)
email.add_progress(85, label="Quarterly KPI Completion Rate", theme="success")

# 4. Export as HTML file
# Will generate "quarterly_report.html" in the default output directory (usually ./output)
file_path = email.export_html("quarterly_report.html")

print(f"Report successfully generated at: {file_path}")

# You can also directly get the HTML string
html_content = email.export_str()
# print(html_content)

Initialize Email object.

Parameters:

Name Type Description Default
title str

Email title, defaults to "Email Report"

'Email Report'

Functions

add_alert(content, alert_type=None, title=None)

Quickly add an alert widget.

Parameters:

Name Type Description Default
content str

Alert content

required
alert_type AlertType

Alert type, defaults to NOTE

None
title str | None

Custom title, optional

None

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> email.add_alert("Task executed successfully!", AlertType.TIP)
>>> email.add_alert("Please check the data", AlertType.WARNING, "Important Notice")
add_button(text, href, background_color=None, text_color=None, width=None, align='left')

Quickly add button widget.

Parameters:

Name Type Description Default
text str

Button display text

required
href str

Link address to jump to after clicking the button

required
background_color str | None

Button background color, optional

None
text_color str | None

Button text color, optional

None
width str | None

Button width, optional

None
align str

Button alignment, defaults to "left"

'left'

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> # Basic button
>>> email.add_button("View Details", "https://example.com/details")
>>> # Custom styled button
>>> email.add_button("Buy Now", "https://shop.example.com",
...                  background_color="#22c55e", text_color="#ffffff",
...                  width="200px", align="center")
add_card(title, content, icon=None, metadata=None)

Quickly add a card widget.

Parameters:

Name Type Description Default
title str

Card title

required
content str

Card content

required
icon str | None

Icon, optional

None
metadata dict[str, str] | None

Metadata dictionary, optional

None

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> email.add_card("System Status", "All services running normally", "✅")
>>> # Card with metadata
>>> metadata = {"CPU": "15%", "Memory": "60%"}
>>> email.add_card("Server Monitoring", "Resource usage status", "🖥️", metadata)
add_chart_from_plt(title=None, description=None, data_summary=None)

Quickly add a matplotlib chart widget.

Parameters:

Name Type Description Default
title str | None

Chart title, optional

None
description str | None

Chart description, optional

None
data_summary str | None

Data summary, optional

None

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> import matplotlib.pyplot as plt
>>> plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
>>> plt.title("Sales Trend")
>>>
>>> email = Email()
>>> email.add_chart_from_plt("Monthly Sales", "Shows sales trend changes")
add_checklist(title='', items=None, show_progress=False, compact_mode=False)

Quickly add checklist widget.

Parameters:

Name Type Description Default
title str

Checklist title, optional

''
items list[tuple[str, bool]] | None

Checklist items list, format: [(text, completed), ...], optional

None
show_progress bool

Whether to show progress statistics, defaults to False

False
compact_mode bool

Whether to use compact mode, defaults to False

False

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> # Basic checklist
>>> email.add_checklist("Task List", [
...     ("Complete Design", True),
...     ("Code Review", False),
...     ("Deploy Testing", False)
... ])
>>> # Checklist with progress statistics
>>> email.add_checklist("Project Progress", [
...     ("Requirements Analysis", True),
...     ("Development Implementation", True),
...     ("Testing Verification", False)
... ], show_progress=True)
add_circular_progress(value, max_value=100.0, label=None, theme=None, size='100px')

Quickly add circular progress bar widget.

Parameters:

Name Type Description Default
value float

Current progress value

required
max_value float

Maximum value, defaults to 100

100.0
label str | None

Progress bar label, optional

None
theme ProgressTheme

Theme, defaults to PRIMARY

None
size str

Circle size, defaults to "100px"

'100px'

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> email.add_circular_progress(85, label="Overall Completion")
>>> email.add_circular_progress(100, theme=ProgressTheme.SUCCESS, size="120px")
add_image(image_url, title=None, description=None, alt_text=None, width=None, height=None, max_width=None, border_radius=None, cache=True, embed=True, show_caption=True)

Quickly add image widget.

Parameters:

Name Type Description Default
image_url str | Path

Image URL string or local file Path object

required
title str | None

Image title, optional

None
description str | None

Image description, optional

None
alt_text str | None

Image alt text, optional

None
width str | None

Image width, like "300px", "100%"

None
height str | None

Image height, like "200px", "auto"

None
max_width str | None

Image maximum width, like "600px"

None
border_radius str | None

Border radius, like "8px", "50%"

None
cache bool

Whether to cache network images, defaults to True

True
embed bool

Whether to embed images, defaults to True

True
show_caption bool

Whether to show title and description, defaults to True

True

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> # Basic usage
>>> email.add_image("https://example.com/image.png")
>>> # Local image
>>> from pathlib import Path
>>> email.add_image(Path("./assets/logo.png"), title="Company Logo")
>>> # Complete options
>>> email.add_image(
...     "https://example.com/product.jpg",
...     title="Product Showcase",
...     description="Latest product showcase image",
...     alt_text="Product Image",
...     width="100%",
...     max_width="600px",
...     border_radius="8px"
... )
add_log(logs, title=None, show_timestamp=True, show_level=True, filter_level=None, max_height='400px')

Quickly add log widget.

Parameters:

Name Type Description Default
logs list[str]

Log list

required
title str | None

Log title, optional

None
show_timestamp bool

Whether to show timestamps

True
show_level bool

Whether to show log levels

True
filter_level LogLevel

Filter level, optional

None
max_height str

Maximum height, defaults to "400px"

'400px'

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> logs = [
...     "2024-01-01 10:00:00.000 | INFO | main:process:10 - Task started",
...     "2024-01-01 10:00:01.000 | WARNING | main:check:20 - Found abnormal data",
...     "2024-01-01 10:00:02.000 | INFO | main:finish:30 - Task completed"
... ]
>>> email.add_log(logs, "Execution Log")
add_metric(title='', metrics=None, layout='horizontal', show_trends=True)

Quickly add metric widget.

Parameters:

Name Type Description Default
title str

Metric group title, optional

''
metrics list[tuple] | None

Metric list, format: [(label, value, unit, trend, trend_type, description), ...], optional

None
layout str

Layout method, 'horizontal' or 'vertical', defaults to 'horizontal'

'horizontal'
show_trends bool

Whether to show trend information, defaults to True

True

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> # Basic metrics
>>> email.add_metric("Core Metrics", [
...     ("Users", 12345, "people"),
...     ("Growth Rate", "15.6", "%", "+2.3%", "success"),
...     ("Revenue", "$1,250,000", "", "+12.3%", "success")
... ])
>>> # Metrics with complete options
>>> email.add_metric(
...     title="System Performance",
...     metrics=[
...         ("CPU Usage", "45.2", "%", "+2.1%", "warning", "Needs attention"),
...         ("Memory Usage", "78.5", "%", "-1.3%", "success", "Performing well"),
...         ("Disk Space", "23.8", "GB", "+5.2GB", "info", "Normal range")
...     ],
...     layout="vertical",
...     show_trends=True
... )
add_progress(value, label=None, max_value=100.0, theme=None, show_percentage=True)

Quickly add a progress bar widget.

Parameters:

Name Type Description Default
value float

Current progress value

required
label str | None

Progress bar label, optional

None
max_value float

Maximum value, defaults to 100

100.0
theme ProgressTheme

Theme, defaults to PRIMARY

None
show_percentage bool

Whether to show percentage

True

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> email.add_progress(75, "Task Completion")
>>> email.add_progress(100, "Download Progress", theme=ProgressTheme.SUCCESS)
add_quote(content, author=None, source=None, quote_type=None)

Quickly add a quote widget.

Parameters:

Name Type Description Default
content str

Quote content

required
author str | None

Author, optional

None
source str | None

Source, optional

None
quote_type StatusType

Quote type, defaults to INFO

None

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> email.add_quote("Success is not final, failure is not fatal", "Churchill")
>>> email.add_quote("Data is the new oil", source="The Economist")
add_separator(separator_type=None, color=None, thickness=None, width=None, margin=None)

Quickly add separator widget.

Parameters:

Name Type Description Default
separator_type SeparatorType

Separator type, defaults to SOLID

None
color str | None

Separator color, optional

None
thickness str | None

Separator thickness, optional

None
width str | None

Separator width, optional

None
margin str | None

Top and bottom margin, optional

None

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> # Basic separator
>>> email.add_separator()
>>> # Custom styled separator
>>> email.add_separator(
...     separator_type=SeparatorType.DASHED,
...     color="#0078d4",
...     thickness="2px",
...     width="80%"
... )
add_status_items(items, title=None, layout=None)

Quickly add a status information widget.

Parameters:

Name Type Description Default
items list[dict[str, str]]

Status item list, each item contains label, value, status (optional)

required
title str | None

Status group title, optional

None
layout LayoutType

Layout type, defaults to VERTICAL

None

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> items = [
...     {"label": "CPU Usage", "value": "15%"},
...     {"label": "Memory Usage", "value": "60%"},
...     {"label": "Disk Space", "value": "80%"}
... ]
>>> email = Email()
>>> email.add_status_items(items, "System Monitoring")
add_table_from_data(data, headers=None, title=None, show_index=False, striped=True, bordered=True, hoverable=True)

Quickly add a table widget.

Parameters:

Name Type Description Default
data list[list[str]]

Table data, two-dimensional list

required
headers list[str] | None

Header list, optional

None
title str | None

Table title, optional

None
show_index bool

Whether to show row index

False
striped bool

Whether to use striped style

True
bordered bool

Whether to show borders

True
hoverable bool

Whether to support hover effects

True

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> data = [["Alice", "100", "Excellent"], ["Bob", "95", "Good"]]
>>> headers = ["Name", "Score", "Grade"]
>>> email.add_table_from_data(data, headers, "Grade Report")
add_table_from_df(df, title=None, show_index=False, striped=True, bordered=True, hoverable=True)

Quickly add a table widget from DataFrame.

Parameters:

Name Type Description Default
df DataFrame

pandas DataFrame object

required
title str | None

Table title, optional

None
show_index bool

Whether to show row index

False
striped bool

Whether to use striped style

True
bordered bool

Whether to show borders

True
hoverable bool

Whether to support hover effects

True

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> import pandas as pd
>>> df = pd.DataFrame({"Name": ["Alice", "Bob"], "Score": [100, 95]})
>>> email = Email()
>>> email.add_table_from_df(df, "Grade Statistics")
add_text(content, text_type=None, color=None, font_size=None, align=None, font_weight=None)

Quickly add a text widget.

Parameters:

Name Type Description Default
content str

Text content

required
text_type TextType

Text type, defaults to TextType.BODY

None
color str | None

Text color, e.g., "#ff0000"

None
font_size str | None

Font size, e.g., "18px"

None
align TextAlign

Text alignment

None
font_weight str | None

Font weight, e.g., "bold"

None

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> # Regular body text
>>> email.add_text("This is regular text")
>>> # Large title
>>> email.add_text("Important Title", TextType.TITLE_LARGE)
>>> # Styled text
>>> email.add_text("Important Notice", color="#ff0000", font_size="18px")
add_timeline(title='', events=None, show_time=False, reverse_order=False)

Quickly add timeline widget.

Parameters:

Name Type Description Default
title str

Timeline title, optional

''
events list[tuple] | None

Events list, format: [(title, time, description, status_type), ...], optional

None
show_time bool

Whether to show timestamps, defaults to False

False
reverse_order bool

Whether to reverse order, defaults to False

False

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> # Basic timeline
>>> email.add_timeline("Project Progress", [
...     ("Project Launch", "2024-01-01", "Project officially started"),
...     ("Requirements Confirmed", "2024-01-15", "Requirements analysis completed"),
...     ("Development Complete", "2024-02-28", "Code development completed")
... ])
>>> # Timeline with timestamps
>>> email.add_timeline("System Log", [
...     ("System Startup", "2024-01-01 09:00", "Service started", "success"),
...     ("Issue Found", "2024-01-01 10:30", "Bug discovered", "error"),
...     ("Issue Fixed", "2024-01-01 11:00", "Fix completed", "success")
... ], show_time=True, reverse_order=True)
add_widget(widget)

Add a single widget to the email.

Parameters:

Name Type Description Default
widget BaseWidget

The widget object to add

required

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> text_widget = TextWidget().set_content("Hello")
>>> email.add_widget(text_widget)
add_widgets(widgets)

Batch add multiple widgets to the email.

Parameters:

Name Type Description Default
widgets list[BaseWidget]

List of widget objects

required

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> widgets = [TextWidget(), TableWidget(), ChartWidget()]
>>> email.add_widgets(widgets)
clear_widgets()

Clear all widgets.

Returns:

Type Description
Email

Returns self to support method chaining

export_html(filename=None, output_dir=None)

Export email as HTML file.

Parameters:

Name Type Description Default
filename str | None

Optional filename, auto-generated if not provided

None
output_dir str | None

Optional output directory, uses default directory from config if not provided

None

Returns:

Type Description
Path

Complete path of exported file

Examples:

Python Console Session
>>> email = Email("Report")
>>> # Use default filename
>>> path = email.export_html()
>>>
>>> # Specify filename and directory
>>> path = email.export_html("my_report.html", "./reports")
export_str()

Export email as HTML text.

Returns:

Type Description
str

Complete HTML email string

Examples:

Python Console Session
>>> email = Email("Preview Test")
>>> html = email.export_str()
>>> print(html[:100])  # Print first 100 characters
get_widget(widget_id)

Get a specific widget by ID.

Parameters:

Name Type Description Default
widget_id str

The widget's ID

required

Returns:

Type Description
BaseWidget | None

The found widget object, or None if it doesn't exist

Examples:

Python Console Session
>>> email = Email()
>>> widget = TextWidget().set_widget_id("my_text")
>>> email.add_widget(widget)
>>> found_widget = email.get_widget("my_text")
get_widget_count()

Get the number of widgets in the current email.

Returns:

Type Description
int

Number of widgets

Examples:

Python Console Session
>>> email = Email()
>>> email.add_widget(TextWidget())
>>> email.add_widget(TableWidget())
>>> print(email.get_widget_count())  # Output: 2
remove_widget(widget_id)

Remove a specific widget by ID.

Parameters:

Name Type Description Default
widget_id str

The ID of the widget to remove

required

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> widget = TextWidget().set_widget_id("my_text")
>>> email.add_widget(widget)
>>> email.remove_widget("my_text")

Set the email footer.

Parameters:

Name Type Description Default
footer_text str | None

Footer text, if None uses default text

required

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> email.set_footer("This report is automatically generated by the data team")
set_subtitle(subtitle)

Set the email subtitle.

Parameters:

Name Type Description Default
subtitle str | None

Subtitle text, if None uses default timestamp

required

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> email.set_subtitle("Data Statistics Report")
set_title(title)

Set the email title.

Parameters:

Name Type Description Default
title str

New email title

required

Returns:

Type Description
Email

Returns self to support method chaining

Examples:

Python Console Session
>>> email = Email()
>>> email.set_title("Daily Data Report - 2024-01-01")