### Install Red Mail Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/getting_started.rst Instructions for installing the Red Mail package using pip and conda. ```console pip install redmail ``` ```console conda install -c conda-forge redmail ``` -------------------------------- ### Configure Email Sender Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/getting_started.rst Examples of configuring the EmailSender class with and without SMTP credentials. ```python from redmail import EmailSender email = EmailSender( host='', port='', username='', password='' ) ``` ```python # Or if your SMTP server does not require credentials email = EmailSender( host='', port='', ) ``` -------------------------------- ### Initialize Email Sender Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/example.rst Demonstrates the basic initialization of the EmailSender object with connection details for sending emails. ```python from redmail import EmailSender email = EmailSender( host='localhost', port=0, username='me@example.com', password='' ) ``` -------------------------------- ### Install Red Mail Source: https://github.com/miksus/red-mail/blob/master/docs/index.rst Provides the command to install the Red Mail package using pip, making it available for use in Python projects. ```console pip install redmail ``` -------------------------------- ### Super Example: Comprehensive Email Sending Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/example.rst A comprehensive example showcasing multiple features including various attachments, embedded images (from file path and PIL Image), embedded plots, embedded tables, parameterized content, and conditional logic within the HTML template. ```python from pathlib import Path from redmail import EmailSender import pandas as pd from PIL import Image import matplotlib.pyplot as plt fig = plt.figure() plt.plot([1, 2, 3]) df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]}) byte_content = Path("a_file.bin").read_bytes() email.send( subject="A lot of stuff!", sender="me@example.com", # Receivers receivers=["you@example.com"], cc=['also@example.com'], bcc=['external@example.com'], # Bodies text=""" Hi {{ friend }}, This email has a lot of stuff! Use HTML to view the awesome content. """, html="""

Hi {{ friend }},

This email has a lot of stuff!

Like this image:

{{ my_image }}

or this image:

{{ my_pillow }}

or this plot:

{{ my_plot }}

or this table:

{{ my_table }}

or this loop:

    {% for value in container %} {% if value > 5 %}
  • {{ value }}
  • {% else %}
  • {{ value }}
  • {% endif %} {% endfor %}
""", # Embedded content body_images={ "my_image": "path/to/image.png", "my_pillow": Image.new('RGB', (100, 30), color = (73, 109, 137)) "my_plot": fig, }, body_tables={ "my_table": df, }, body_params={ "friend": "Jack", "container": [1, 3, 5, 7, 9], }, attachments={ "data.csv": df, "file.txt": "This is file content", "file.html": Path("path/to/a_file.html"), "file.bin": byte_content, } ) ``` -------------------------------- ### HTML Email Template Example Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/templating.rst An example of an HTML template for an email, demonstrating the use of Jinja variables for dynamic content such as participant name, event details, and organizer. ```html

Hi {{ participant }}!

Thank you for being a valuable member of our community! We are organizing an event {{ event_name }} and we would like to invite you.

Kind regards,
{{ organizer }}

``` -------------------------------- ### Send Email Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/getting_started.rst Basic example of sending an email using the send method of the EmailSender class. ```python email.send( subject='email subject', sender="me@example.com", receivers=['you@example.com'], text="Hi, this is an email." ) ``` -------------------------------- ### Send Simple Email Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/example.rst Shows how to send a basic email with both plain text and HTML content. ```python email.send( subject="An email", sender="me@example.com", receivers=['you@example.com'], text="Hi, this is an email.", html="

Hi,

this is an email.

" ) ``` -------------------------------- ### Build Documentation with Tox Source: https://github.com/miksus/red-mail/blob/master/CONTRIBUTING.md Installs tox and builds the project's documentation. This command is used to generate the HTML documentation files. ```python pip install tox python -m tox -e docs ``` -------------------------------- ### Install Red Mail Source: https://github.com/miksus/red-mail/blob/master/README.md Installs the Red Mail library using pip. This is the primary method for obtaining the library. ```shell pip install redmail ``` -------------------------------- ### Parametrize Email Content Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/example.rst Demonstrates how to use parameters within the email's text and HTML content for dynamic personalization. ```python email.send( subject="Email subject", sender="me@example.com", receivers=["you@example.com"], text="Hi {{ friend }}, nice to meet you.", html="

Hi {{ friend }}, nice to meet you

", body_params={ "friend": "Jack" } ) ``` -------------------------------- ### Run Tests with Tox Source: https://github.com/miksus/red-mail/blob/master/CONTRIBUTING.md Installs tox and runs all project tests. Tox is a tool that automates testing in multiple Python environments. ```python pip install tox python -m tox ``` -------------------------------- ### Install Red Mail with Styling Dependencies Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/embed/table.rst Installs Red Mail along with the necessary `css_inline` package for using Pandas Styler objects to style HTML tables in emails. ```shell pip install redmail[style] ``` -------------------------------- ### Send Email using Gmail Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/config.rst Provides a code example for sending emails via Gmail using Red Mail. It highlights the need for a Gmail username, an app password, and the `gmail` sender instance. ```python from redmail import gmail gmail.username = 'example@gmail.com' # Your Gmail address gmail.password = '' # And then you can send emails gmail.send( subject="Example email", receivers=['you@example.com'], text="Hi, this is an email." ) ``` -------------------------------- ### Send Email with Attachments Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/example.rst Illustrates sending an email with various types of attachments, including CSV files (as Path objects and Pandas DataFrames) and HTML content. ```python from pathlib import Path import pandas as pd email.send( subject="Email subject", sender="me@example.com", receivers=["you@example.com"], text="Hi, this is a simple email.", attachments={ 'myfile.csv': Path("path/to/data.csv"), 'myfile.xlsx': pd.DataFrame({'A': [1, 2, 3]}), 'myfile.html': '

This is content of an attachment

' } ) ``` -------------------------------- ### Embed Image in Email Body Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/example.rst Demonstrates how to embed an image directly into the HTML body of an email using a placeholder. ```python import pandas as pd email.send( subject="Email subject", sender="me@example.com", receivers=["you@example.com"], html="""

Hi,

have you seen this?

{{ myimg }} """, body_images={"myimg": "path/to/my/image.png"} ) ``` -------------------------------- ### Optional Dependencies Source: https://github.com/miksus/red-mail/blob/master/requirements/coverage.txt This section outlines optional dependencies that can be installed to extend the functionality of the Red-Mail project. These include libraries for data manipulation (pandas), plotting (matplotlib), image processing (Pillow), Excel file handling (openpyxl), and inline CSS conversion (css_inline). ```python pandas matplotlib Pillow openpyxl css_inline ``` -------------------------------- ### Send Templated Error Alerts with Traceback Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/cookbook.rst Shows how to create and send templated error alerts that include the full traceback of an exception. This is useful for long-running programs like web applications to get detailed error information via email. ```python from redmail import EmailSender error_email = EmailSender(...) error_email.sender = 'me@example.com' error_email.receivers = ['me@example.com'] error_email.html = """

An error encountered

{{ error }} """ try: raise RuntimeError("Oops") except: # Send an email including the traceback error_email.send(subject="Fail: doing stuff failed") ``` -------------------------------- ### EmailHandler: Basic Usage Source: https://github.com/miksus/red-mail/blob/master/docs/extensions/logging.rst Demonstrates the basic setup of the EmailHandler to send a single log record per email. It requires specifying connection details, subject, sender, and receivers. ```python import logging from redmail import EmailHandler hdlr = EmailHandler( host="localhost", port=0, subject="A log record", sender="no-reply@example.com", receivers=["me@example.com"], ) logger = logging.getLogger(__name__) logger.addHandler(hdlr) # To use: logger.warning("A warning happened") ``` -------------------------------- ### Basic Email Sending (Red Mail) Source: https://github.com/miksus/red-mail/blob/master/docs/index.rst Illustrates the simplified approach to sending emails using the Red Mail library. It shows how to initialize an EmailSender and send a basic email with both plain text and HTML content. ```python from redmail import EmailSender email = EmailSender(host="localhost", port=0) email.send( subject="An example email", sender="me@example.com", receivers=['you@example.com'], text="Hello!", html="

Hello!

" ) ``` -------------------------------- ### Send Email using Outlook Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/config.rst Demonstrates how to send an email using the pre-configured Outlook sender instance. It requires setting the username and password for the Outlook account. ```python from redmail import outlook outlook.username = 'example@hotmail.com' outlook.password = '' outlook.send( subject="Example email", receivers=['you@example.com'], text="Hi, this is an email." ) ``` -------------------------------- ### Embed Matplotlib Plot in Email Body Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/example.rst Shows how to embed a Matplotlib plot directly into the HTML body of an email. ```python import matplotlib.pyplot as plt fig = plt.figure() plt.plot([1,2,3,2,3]) email.send( subject="Email subject", sender="me@example.com", receivers=["you@example.com"], html="""

Hi,

have you seen this?

{{ myplot }} """, body_images={"myplot": fig} ) ``` -------------------------------- ### Basic Email Sending Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/sending.rst Demonstrates the fundamental usage of the EmailSender class to send a simple email. It requires initializing EmailSender with host and port, then calling the send method with subject, sender, and receivers. ```python from redmail import EmailSender email = EmailSender(host='localhost', port=0) email.send( subject='email subject', sender="me@example.com", receivers=['you@example.com'] ) ``` -------------------------------- ### Embed Pandas DataFrame in Email Body Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/example.rst Illustrates embedding a Pandas DataFrame as an HTML table within the email body. ```python import pandas as pd email.send( subject="Email subject", sender="me@example.com", receivers=["you@example.com"], html="""

Hi,

have you seen this?

{{ mytable }} """, body_tables={"mytable": pd.DataFrame({'a': [1,2,3], 'b': [1,2,3]})} ) ``` -------------------------------- ### Sphinx Configuration Dependencies Source: https://github.com/miksus/red-mail/blob/master/requirements/docs.txt Lists the Python package dependencies required for building the Sphinx documentation for this project. These packages provide themes, extensions for features like code copying, and overall structure. ```python sphinx >= 1.7.5 pydata-sphinx-theme sphinx_material sphinx-copybutton sphinx_book_theme ``` -------------------------------- ### Send Email with HTML Template Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/templating.rst Demonstrates how to send an email using a specified HTML template and provide parameters to populate the template's variables. This is a core functionality for sending personalized emails. ```python email.send( subject='email subject', receivers=['first.last@example.com'], html_template='event_card.html', body_params={ 'participant': 'Jack', 'event_name': 'Open data', 'organizer': 'Organization.org' } ) ``` -------------------------------- ### MultiEmailHandler: Basic Usage Source: https://github.com/miksus/red-mail/blob/master/docs/extensions/logging.rst Demonstrates the setup for MultiEmailHandler, which sends multiple log records in a single email. The 'capacity' parameter determines how many records trigger an email. ```python import logging from redmail import MultiEmailHandler hdlr = MultiEmailHandler( capacity=2, # Sends email after every second record host="localhost", port=0, subject="log records", sender="no-reply@example.com", receivers=["me@example.com"], ) logger = logging.getLogger(__name__) logger.addHandler(hdlr) # To use: logger.warning("A warning happened") logger.warning("Another warning happened") # (Now an email should have been sent) # You may also manually flush logger.warning("A warning happened") hdlr.flush() ``` -------------------------------- ### Basic Email Sending (Red Mail) Source: https://github.com/miksus/red-mail/blob/master/README.md Illustrates the simplified email sending process using the Red Mail library. It shows how to initialize the EmailSender and send a basic email with text and HTML content. ```python from redmail import EmailSender email = EmailSender(host="localhost", port=0) email.send( subject="An example email", sender="me@example.com", receivers=['first.last@example.com'], text="Hello!", html="

Hello!

" ) ``` -------------------------------- ### Set Template Paths Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/templating.rst Configures Red Mail to use specified directories for HTML and text email templates. Red Mail will automatically create Jinja environments based on these paths. ```python from redmail import EmailSender email = EmailSender(host="localhost", port=0) email.set_template_paths( html="path/html/templates", text="path/text/templates", ) ``` -------------------------------- ### Basic Email Sending (Standard Library) Source: https://github.com/miksus/red-mail/blob/master/docs/index.rst Demonstrates the traditional, more verbose method of sending emails using Python's built-in smtplib and email.mime modules. This highlights the complexity Red Mail aims to simplify. ```python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText msg = MIMEMultipart('alternative') msg['Subject'] = 'An example email' msg['From'] = 'me@example.com' msg['To'] = 'you@example.com' part1 = MIMEText("Hello!", 'plain') part2 = MIMEText("

Hello!

", 'html') msg.attach(part1) msg.attach(part2) # Send the message via our own SMTP server. s = smtplib.SMTP('localhost', port=0) s.send_message(msg) s.quit() ``` -------------------------------- ### Red Mail Text Body Formatting Issue Source: https://github.com/miksus/red-mail/blob/master/docs/faq.rst Illustrates how lines starting with 'From' in the text body of an email sent via Red Mail can be automatically prefixed with '>' by the underlying smtplib. This is a security measure to prevent email body injection and cannot be disabled. Using an HTML body is recommended as a workaround. ```python from redmail import EmailSender email = EmailSender(...) email.send( subject="An example email", sender="me@example.com", receivers=['me@example.com'], text="Hi!\nFrom what we discussed..." ) ``` ```console Hi! >From what we discussed... ``` -------------------------------- ### Red Mail STARTTLS Configuration Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/client.rst Configures the EmailSender to use STARTTLS for connecting to the SMTP server. This is the default behavior but can be explicitly set. ```python from redmail import EmailSender from smtplib import SMTP email = EmailSender( host="smtp.example.com", port=587, cls_smtp=SMTP, use_starttls=True ) ``` -------------------------------- ### Testing Email Sending with get_message Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/testing.rst Demonstrates how to use the `get_message` method of `EmailSender` to generate email messages for testing purposes without sending them. This is useful for unit tests where actual email delivery is not desired. It shows how to instantiate `EmailSender` with dummy host/port and then assert the generated message content. ```python from redmail import EmailSender # Just put something as host and port email = EmailSender(host="localhost", port=0) msg = email.get_message( subject='email subject', sender="me@example.com", receivers=['you@example.com'], text="Hi, this is an email.", ) assert str(msg) == """From: me@example.com Subject: Some news To: you@example.com Message-ID: <167294165062.31860.1664530310632362057@LAPTOP-1234GML0> Date: Sun, 31 Jan 2021 06:56:46 -0000 Content-Type: text/plain; charset=\"utf-8\" Content-Transfer-Encoding: 7bit MIME-Version: 1.0 Hi, nice to meet you. """ ``` -------------------------------- ### Email with Jinja Loops and Control Flow Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/jinja_support.rst Illustrates advanced Jinja templating by including a `for` loop to iterate over a dictionary of colleagues and an `if` statement to conditionally display content. This showcases the power of Jinja for dynamic email generation. ```python email.send( subject='email subject', receivers=['first.last@example.com'], html="""

Hi!

Soon you will meet my team. Here is a quick introduction:

    {% for colleague in colleagues.items() %}
  • {{ colleague }}: {{ description }}
  • {% endfor %}
{% if confidential %}

This message is confidential.

{% endif %}

Kind regards
{{ sender.full_name }}

"", body_params={ 'colleagues': {'Jack': 'Developer', 'John': 'CEO'}, 'confidential': False } ) ``` -------------------------------- ### Send Personalized Email Campaign Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/cookbook.rst Demonstrates how to send personalized emails to a list of customers using HTML templates. It covers setting template paths, defining an HTML template with placeholders, and iterating through customers to send customized emails with dynamic content and images. ```python from redmail import EmailSender email = EmailSender(...) email.receivers = ['we@example.com'] email.set_template_paths( html="path/to/campaigns" ) ``` ```html

Thank you, {{ customer }}, for being awesome!

We are pleased to inform you that we have a lot of products in huge discounts.

    {% for product, discount, in discounts.items() %}
  • {{ product }}: {{ '{:.0f} %'.format(discount * 100) }}
  • {% endfor %}

Kind regards, We Ltd.

``` ```python discounts = {'shoes': 0.2, 'shirts': 0.4} customers = ['cust1@example.com', 'cust2@example.com', ...] for customer in customers: email.send( subject="Summer Sale!", html_template="summer_sale.html", body_params={ "customer": customer, "discounts": discounts }, body_images={ "company_logo": "path/to/logo.png" } ) ``` -------------------------------- ### Package Requirements Source: https://github.com/miksus/red-mail/blob/master/requirements/coverage.txt This section lists the essential package requirements for the Red-Mail project. Jinja2 is a core dependency, likely used for templating emails. ```python jinja2 ``` -------------------------------- ### Sending Email with Red-Mail Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/cookbook.rst Demonstrates sending an email using the EmailSender class, specifying recipients via a group name. ```python email = EmailSender(host="localhost", port=0) email.receivers = { "developers": ["dev1@example.com", "dev2@example.com"] } email.send( subject="Important news", receivers="developers", cc="managers", ... ) ``` -------------------------------- ### Parametrize Email with Jinja Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/jinja_support.rst Demonstrates sending an email with HTML and text bodies parameterized using Jinja variables. The `body_params` dictionary provides values for the template variables. ```python email.send( subject='email subject', receivers=['first.last@example.com'], html="""

Hi {{ client }},

we are opening the source of {{ project_name }}.

Kind regards
{{ company }}

""", text=""" Hi {{ client }}, we are opening the source of {{ project_name }}. Kind regards, {{ company }} """, body_params={ 'client': 'Customer LTD', 'project_name': 'Red Mail', 'company': 'Company LTD', } ) ``` -------------------------------- ### Create Custom Distribution Lists with EmailSender Subclass Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/cookbook.rst Illustrates how to create a custom distribution list logic by subclassing the `EmailSender` class. This allows pre-defined groups of recipients to be managed and retrieved for sending emails. ```python from redmail import EmailSender class DistributionSender(EmailSender): """Send email using pre-defined distribution lists""" def __init__(self, *args, distributions:dict, **kwargs): super().__init__(*args, **kwargs) self.distributions = distributions def get_receivers(self, receiver_list): if receiver_list: return self.distributions[receiver_list] def get_cc(self, receiver_list): if receiver_list: return self.distributions[receiver_list] def get_bcc(self, receiver_list): if receiver_list: return self.distributions[receiver_list] # Then to use it: email = DistributionSender( host="localhost", port=0, distributions={ "managers": ["boss1@example.com", "boss2@example.com"], ``` -------------------------------- ### Red Mail EmailSender API Source: https://github.com/miksus/red-mail/blob/master/docs/references.rst API documentation for the EmailSender class in Red Mail, detailing its methods for sending emails. ```APIDOC EmailSender: __init__(host: str, port: int, username: Optional[str] = None, password: Optional[str] = None, ssl: bool = False, tls: bool = False, **kwargs) Initializes the EmailSender with connection details. host: SMTP server hostname. port: SMTP server port. username: Username for authentication (optional). password: Password for authentication (optional). ssl: Use SSL for connection (default: False). tls: Use TLS for connection (default: False). send( subject: str, sender: Union[str, EmailAddress], receivers: Union[str, EmailAddress, List[Union[str, EmailAddress]]], text: Optional[str] = None, html: Optional[str] = None, attachments: Optional[List[Union[str, Path, BytesIO]]] = None, cc: Optional[Union[str, EmailAddress, List[Union[str, EmailAddress]]]] = None, bcc: Optional[Union[str, EmailAddress, List[Union[str, EmailAddress]]]] = None, reply_to: Optional[Union[str, EmailAddress, List[Union[str, EmailAddress]]]] = None, headers: Optional[Dict[str, str]] = None, **kwargs ) Sends an email. subject: Email subject. sender: Sender's email address. receivers: List of recipient email addresses. text: Plain text body of the email (optional). html: HTML body of the email (optional). attachments: List of attachments (file paths or BytesIO objects) (optional). cc: CC recipients (optional). bcc: BCC recipients (optional). reply_to: Reply-to addresses (optional). headers: Additional email headers (optional). connect(**kwargs) Establishes a connection to the SMTP server. quit() Closes the connection to the SMTP server. ``` -------------------------------- ### MultiEmailHandler: Using EmailSender Instance Source: https://github.com/miksus/red-mail/blob/master/docs/extensions/logging.rst Shows how to provide an existing EmailSender instance to the MultiEmailHandler. Similar to EmailHandler, this allows for reusing sender configurations. ```python from redmail import EmailSender hdlr = MultiEmailHandler( email=EmailSender(host="localhost", port=0) subject="Log records", receivers=["me@example.com"], ) ``` -------------------------------- ### Testing Tools Source: https://github.com/miksus/red-mail/blob/master/requirements/coverage.txt This section details the testing frameworks used in the Red-Mail project. Pytest is the primary testing framework, and pytest-cov is used for measuring code coverage during tests. ```python pytest pytest-cov ``` -------------------------------- ### EmailHandler: Using EmailSender Instance Source: https://github.com/miksus/red-mail/blob/master/docs/extensions/logging.rst Shows how to pass an existing EmailSender instance to the EmailHandler. This allows for reusing a pre-configured sender and setting additional email attributes on the handler. ```python from redmail import EmailSender hdlr = EmailHandler( email=EmailSender(host="localhost", port=0) subject="A log record", receivers=["me@example.com"], ) ``` -------------------------------- ### Red Mail LMTP Configuration Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/client.rst Configures the EmailSender to use LMTP for connecting to the mail server. This involves specifying the LMTP client class. ```python from redmail import EmailSender from smtplib import LMTP email = EmailSender( host="smtp.example.com", port=587, cls_smtp=LMTP ) ``` -------------------------------- ### Set Jinja Environments Directly Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/templating.rst Allows direct assignment of pre-configured Jinja2 Environment objects to Red Mail's HTML and text template attributes. This provides more control over Jinja's behavior. ```python import jinja2 # Create an env jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader("path/to/templates")) email_sender.templates_html = jinja_env email_sender.templates_text = jinja_env ``` -------------------------------- ### Sending Email with CC and BCC Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/sending.rst Shows how to add recipients to the Carbon Copy (CC) and Blind Carbon Copy (BCC) fields of an email using the 'cc' and 'bcc' arguments. ```python email.send( subject='email subject', sender="me@example.com", receivers=['you@example.com'], cc=['also@example.com'], bcc=['outsider@example.com'] ) ``` -------------------------------- ### Red Mail Logging Handlers Source: https://github.com/miksus/red-mail/blob/master/docs/references.rst API documentation for Red Mail's logging handlers, EmailHandler and MultiEmailHandler, for capturing email sending events. ```APIDOC EmailHandler: __init__(sender: str, receivers: List[str], subject: str, host: str, port: int, **kwargs) Initializes an EmailHandler to send logs via email. sender: Sender's email address. receivers: List of recipient email addresses for logs. subject: Subject line for log emails. host: SMTP server hostname. port: SMTP server port. MultiEmailHandler: __init__(handlers: List[EmailHandler]) Initializes a MultiEmailHandler to manage multiple EmailHandlers. handlers: A list of EmailHandler instances. ``` -------------------------------- ### Red Mail SMTP TLS Configuration Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/client.rst Configures the EmailSender to use SMTP TLS for connecting to the SMTP server. This disables STARTTLS. ```python from redmail import EmailSender email = EmailSender( host="smtp.example.com", port=587, use_starttls=False ) ``` -------------------------------- ### Sending Email Without Subclassing Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/cookbook.rst Illustrates sending emails without subclassing, by directly configuring recipient lists for different groups. ```python managers = EmailSender(host="localhost", port=0) managers.receivers = ["boss1@example.com", "boss2@example.com"] developers = EmailSender(host="localhost", port=0) developers.receivers = ["dev1@example.com", "dev2@example.com"] # Send an email to the developers developers.send( subject="Important news" ) ``` -------------------------------- ### Send Email Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/sending.rst Demonstrates how to send an email with a subject, sender, and receivers. This function is called multiple times to send emails to different recipients. ```python email.send( subject='email subject', sender="me@example.com", receivers=['you@example.com'] ) email.send( subject='email subject', sender="me@example.com", receivers=['they@example.com'] ) ``` -------------------------------- ### Text Size Roles Source: https://github.com/miksus/red-mail/blob/master/docs/s5defs.txt Defines custom roles for specifying text sizes in S5/HTML data. These roles allow for granular control over font scaling within the presentation. ```python .. role:: huge .. role:: big .. role:: small .. role:: tiny ``` -------------------------------- ### Testing Email Sending by Subclassing EmailSender Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/testing.rst Presents an alternative testing strategy by creating a subclass of `EmailSender` and overriding the `send_message` method to store messages. This method allows for direct access to the captured messages via an instance attribute, simplifying testing assertions. ```python from redmail import EmailSender class MockSender(EmailSender): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.messages = [] def send_message(self, msg): self.messages.append(msg) # Just put something as host and port email = MockSender(host="localhost", port=0) email.send( subject='email subject', sender="me@example.com", receivers=['you@example.com'], text="Hi, this is an email.", ) msgs = email.messages assert msgs == ["""From: me@example.com Subject: Some news To: you@example.com Message-ID: <167294165062.31860.1664530310632362057@LAPTOP-1234GML0> Date: Sun, 31 Jan 2021 06:56:46 -0000 Content-Type: text/plain; charset=\"utf-8\" Content-Transfer-Encoding: 7bit MIME-Version: 1.0 Hi, nice to meet you. """] ``` -------------------------------- ### Set Table Template Paths Source: https://github.com/miksus/red-mail/blob/master/docs/tutorials/templating.rst Specifies custom directories for HTML and text table templates, which are used for rendering embedded tables within emails. This extends the default templating capabilities. ```python email.set_template_paths( html_table="path/html/tables", text_table="path/text/tables", ) ```