### Install Python Emails with Async Sending Source: https://github.com/lavr/python-emails/blob/master/docs/install.md Install the library to enable asynchronous email sending capabilities using the send_async() method. ```bash pip install "emails[async]" ``` -------------------------------- ### Install Core Python Emails Source: https://github.com/lavr/python-emails/blob/master/docs/install.md Install the lightweight core library for building and sending email messages. ```bash pip install emails ``` -------------------------------- ### Jinja2 Template Example Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Create and send an email using Jinja2 templates for the HTML body and subject. Requires Jinja2 to be installed. ```python from emails.template import JinjaTemplate msg = emails.Message( html=JinjaTemplate("

Hello {{ name }}!

"), subject=JinjaTemplate("Welcome, {{ name }}"), mail_from="noreply@example.com" ) msg.send(render={"name": "Alice"}, smtp={"host": "localhost"}) ``` -------------------------------- ### Install Template Dependencies Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Install the necessary dependencies for using Jinja2 templates with the emails library. ```bash pip install "emails[jinja]" ``` -------------------------------- ### Install Python Emails with Jinja2 Templates Source: https://github.com/lavr/python-emails/blob/master/docs/install.md Install the library to enable the use of Jinja2 templates, including the T() shortcut for template rendering. ```bash pip install "emails[jinja]" ``` -------------------------------- ### Install Python Emails with HTML Features Source: https://github.com/lavr/python-emails/blob/master/docs/install.md Install the library with support for HTML transformations like CSS inlining, image embedding, and loading from URLs or files. ```bash pip install "emails[html]" ``` -------------------------------- ### Send Email using STARTTLS Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Use STARTTLS (typically on port 587) by setting `tls=True`. The connection starts in plain text and is then upgraded to TLS. ```python message.send(smtp={"host": "smtp.example.com", "port": 587, "tls": True, "user": "me", "password": "secret"}) ``` -------------------------------- ### Async SMTP Backend Connection and Sending Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Establish an asynchronous SMTP connection using AsyncSMTPBackend for sending emails. Requires 'aiosmtplib' to be installed. ```python from emails.backend.smtp.aio_backend import AsyncSMTPBackend async with AsyncSMTPBackend(host="smtp.example.com", port=587, tls=True, user="me", password="secret") as backend: response = await backend.sendmail( from_addr="sender@example.com", to_addrs=["recipient@example.com"], msg=message ) ``` -------------------------------- ### MakoTemplate Class Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Use MakoTemplate for emails with Mako syntax. This requires the 'mako' package to be installed. ```APIDOC ## MakoTemplate(template_text, **kwargs) ### Description Template using [Mako](https://www.makotemplates.org/) syntax. Requires the `mako` package. ### Parameters * **template_text** (string) - Mako template string. * **kwargs** - Additional parameters passed to `mako.template.Template`. ``` -------------------------------- ### StringTemplate Example Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Create an email using Python's built-in string.Template syntax for the HTML body. Undefined variables are left as-is by default. ```python from emails.template import StringTemplate msg = emails.Message( html=StringTemplate("

Hello $name!

"), mail_from="noreply@example.com" ) ``` -------------------------------- ### Send HTML email with attachments using standard library Source: https://github.com/lavr/python-emails/blob/master/docs/faq.md This example demonstrates manual MIME construction and SMTP session management using Python's standard library. It requires explicit handling of headers, message parts, and SMTP commands. ```python import os import smtplib from email.utils import formataddr, formatdate, COMMASPACE from email.header import Header from email import encoders from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.mime.image import MIMEImage import jinja2 sender_name, sender_email = "CI", "ci@mycompany.com" recipient_addr = ["somebody@mycompany.com"] j = jinja2.Environment() ctx = {"project_name": "user/project1", "build_id": 121} html = j.from_string( "

Build passed: {{ project_name }} " " ...

" ).render(**ctx) text = j.from_string("Build passed: {{ project_name }} ...").render(**ctx) subject = j.from_string( "Passed: {{ project_name }}#{{ build_id }}" ).render(**ctx) encoded_name = Header(sender_name, "utf-8").encode() msg_root = MIMEMultipart("mixed") msg_root["Date"] = formatdate(localtime=True) msg_root["From"] = formataddr((encoded_name, sender_email)) msg_root["To"] = COMMASPACE.join(recipient_addr) msg_root["Subject"] = Header(subject, "utf-8") msg_root.preamble = "This is a multi-part message in MIME format." msg_related = MIMEMultipart("related") msg_root.attach(msg_related) msg_alternative = MIMEMultipart("alternative") msg_related.attach(msg_alternative) msg_text = MIMEText(text.encode("utf-8"), "plain", "utf-8") msg_alternative.attach(msg_text) msg_html = MIMEText(html.encode("utf-8"), "html", "utf-8") msg_alternative.attach(msg_html) with open("icon.png", "rb") as fp: msg_image = MIMEImage(fp.read()) msg_image.add_header("Content-ID", "") msg_related.attach(msg_image) mail_server = smtplib.SMTP("smtp.mycompany.com", 587) mail_server.ehlo() try: mail_server.starttls() mail_server.ehlo() except smtplib.SMTPException as e: print(e) mail_server.login("ci", "secret") mail_server.send_message(msg_root) mail_server.quit() ``` -------------------------------- ### Use Jinja Templates for Email Content Source: https://github.com/lavr/python-emails/blob/master/docs/examples.rst Create email messages using Jinja templates for dynamic subjects and HTML bodies. Requires installing 'emails[jinja]'. ```python from emails.template import JinjaTemplate as T message = emails.html(subject=T('Payment Receipt No.{{ billno }}'), html=T('

Dear {{ name }}! This is a receipt...'), mail_from=('ABC', 'robot@mycompany.com')) message.send(to=('John Brown', 'jbrown@gmail.com'), render={'name': 'John Brown', 'billno': '141051906163'}) ``` -------------------------------- ### Send Email using Implicit SSL Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Use implicit SSL (typically on port 465) by setting `ssl=True` in the SMTP configuration. This encrypts the connection from the start. ```python message.send(smtp={"host": "mail.example.com", "port": 465, "ssl": True, "user": "me", "password": "secret"}) ``` -------------------------------- ### Message.send_async Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Sends the email message asynchronously via SMTP. Requires the 'async' extra to be installed. ```APIDOC ## Message.send_async(to=None, set_mail_to=True, mail_from=None, set_mail_from=False, render=None, smtp_mail_options=None, smtp_rcpt_options=None, smtp=None) ### Description Send the message via SMTP asynchronously. Requires `aiosmtplib` (install with `pip install "emails[async]"`). Parameters are the same as [`send()`](#Message.send), except `smtp` accepts a dict or an `AsyncSMTPBackend` instance. When `smtp` is a dict, a temporary `AsyncSMTPBackend` is created and closed after sending. When an existing backend is passed, the caller is responsible for closing it. ### Returns [`SMTPResponse`](#SMTPResponse) or `None` ### Request Example ```python response = await msg.send_async( to="user@example.com", smtp={"host": "smtp.example.com", "port": 587, "tls": True, "user": "login", "password": "secret"} ) ``` ### Example with shared backend ```python from emails.backend.smtp.aio_backend import AsyncSMTPBackend async with AsyncSMTPBackend(host="smtp.example.com", port=587, tls=True, user="login", password="secret") as backend: for msg in messages: await msg.send_async(smtp=backend) ``` ``` -------------------------------- ### Flask Integration with flask-emails Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Integrate emails into Flask applications using the flask-emails extension. This example shows basic message creation and sending. ```python from flask_emails import Message message = Message( html="

Hello!

", subject="Test", mail_from="sender@example.com" ) message.send(to="user@example.com") ``` -------------------------------- ### Get Raw Email Content as Standard Library Message Object Source: https://github.com/lavr/python-emails/blob/master/docs/quickstart.md Obtain a standard library email.message.Message object using as_message() for inspection or manipulation. ```python msg = message.as_message() print(msg["Subject"]) print(msg["From"]) ``` -------------------------------- ### Get Raw Email Content as String Source: https://github.com/lavr/python-emails/blob/master/docs/quickstart.md Convert the message object to its raw RFC 822 string representation using as_string(). ```python raw = message.as_string() print(raw) ``` -------------------------------- ### Build and Send First Email with Attachment Source: https://github.com/lavr/python-emails/blob/master/README.rst Demonstrates building an HTML email with a subject, sender, HTML content, and attaching a file. It then sends the email via SMTP, asserting a successful response. ```python import emails message = emails.html( subject="Your receipt", html="

Hello!

Your payment was received.

", mail_from=("Billing", "billing@example.com"), ) message.attach(filename="receipt.pdf", data=open("receipt.pdf", "rb")) response = message.send( to="customer@example.com", smtp={ "host": "smtp.example.com", "port": 587, "tls": True, "user": "billing@example.com", "password": "app-password", }, ) assert response.status_code == 250 ``` -------------------------------- ### Create Message instance with emails.html Source: https://github.com/lavr/python-emails/blob/master/docs/api.md The emails.html function is a convenience wrapper for creating a Message instance. It accepts the same parameters as the Message constructor. ```python msg = emails.html( html="

Hello!

", subject="Test", mail_from="sender@example.com" ) ``` -------------------------------- ### Load Message from URL Source: https://github.com/lavr/python-emails/blob/master/docs/transformations.md Use the `from_url` loader to fetch HTML content directly from a web address. Ensure the URL points to a valid HTML resource. ```python import emails.loader message = emails.loader.from_url(url="http://xxx.github.io/newsletter/2015-08-14/index.html") ``` -------------------------------- ### Create a new email message Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Instantiate the Message class with basic email components like HTML content, subject, sender, and recipient. ```python import emails msg = emails.Message( html="

Hello, World!

", subject="Test Email", mail_from=("Sender", "sender@example.com"), mail_to="recipient@example.com" ) ``` -------------------------------- ### Load Email from Directory Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Load an email template from a local directory, automatically looking for index.html or index.htm. Message parameters can be specified during loading. ```python message = emails.loader.from_directory( "/path/to/email-template/", message_params={"subject": "Welcome", "mail_from": "hello@example.com"} ) ``` -------------------------------- ### Create HTML Message from File Source: https://github.com/lavr/python-emails/blob/master/docs/quickstart.md Creates an HTML email message by reading content from an HTML file. Ensure the file is accessible. ```python message = emails.html( html=open("letter.html"), subject="Newsletter", mail_from="newsletter@example.com" ) ``` -------------------------------- ### Load Message from Directory Source: https://github.com/lavr/python-emails/blob/master/docs/transformations.md Load message content from a directory. The directory must contain at least one file with an '.html' extension. ```python message = emails.loader.from_directory('/home/user/design_pack') ``` -------------------------------- ### AsyncSMTPBackend Class Source: https://github.com/lavr/python-emails/blob/master/docs/api.md The AsyncSMTPBackend class manages asynchronous SMTP connections using `aiosmtplib`. It supports `async with` for automatic connection cleanup and provides a `sendmail` method for sending messages. ```APIDOC ## Class AsyncSMTPBackend For async sending via [`Message.send_async()`](#Message.send_async). Requires `aiosmtplib` (install with `pip install "emails[async]"`). ### Initialization ```python AsyncSMTPBackend(ssl=False, fail_silently=True, mail_options=None, **kwargs) ``` Manages an async SMTP connection. Supports `async with` for automatic cleanup. * **Parameters:** * **host** (str) – SMTP server hostname. * **port** (int) – SMTP server port. * **ssl** (bool) – Use implicit TLS (SMTPS). * **tls** (bool) – Use STARTTLS after connecting. * **user** (str) – SMTP username for authentication. * **password** (str) – SMTP password for authentication. * **timeout** (int) – Connection timeout in seconds (default: `5`). * **fail_silently** (bool) – If `True` (default), SMTP errors are captured in the response rather than raised. * **mail_options** (list | None) – Default SMTP MAIL command options. ### Methods #### *async* sendmail(from_addr, to_addrs, msg, mail_options=None, rcpt_options=None) Send a message. Automatically retries once on server disconnect. * **Parameters:** * **from_addr** (str) - The sender's email address. * **to_addrs** (list[str]) - A list of recipient email addresses. * **msg** (Message) - The email message object to send. * **mail_options** (list | None) - Specific MAIL command options for this send operation. * **rcpt_options** (list | None) - Specific RCPT command options for this send operation. * **Returns:** [`SMTPResponse`](#SMTPResponse) or `None` #### *async* close() Close the SMTP connection. ### Example ```python from emails.backend.smtp.aio_backend import AsyncSMTPBackend async with AsyncSMTPBackend(host="smtp.example.com", port=587, tls=True, user="me", password="secret") as backend: response = await backend.sendmail( from_addr="sender@example.com", to_addrs=["recipient@example.com"], msg=message ) ``` ``` -------------------------------- ### Send Email with Default SMTP Configuration Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Use this when you need to send an email with a standard SMTP configuration managed internally by the library. ```python response = message.send( to="user@example.com", smtp={"host": "smtp.example.com", "port": 587, "tls": True, "user": "me", "password": "secret"} ) ``` -------------------------------- ### Send Email with SMTP Configuration Source: https://github.com/lavr/python-emails/blob/master/docs/examples.rst Send an email directly via an SMTP server, specifying host, port, SSL, user, and password. Asserts the success status code. ```python r = message.send(to=('John Brown', 'jbrown@gmail.com'), render={'name': 'John'}, smtp={'host':'smtp.mycompany.com', 'port': 465, 'ssl': True, 'user': 'john', 'password': '***'}) assert r.status_code == 250 ``` -------------------------------- ### Load Message from EML File Source: https://github.com/lavr/python-emails/blob/master/docs/transformations.md Load message content from a .eml file using the `from_rfc822` loader. This functionality is experimental. ```python message = emails.loader.from_rfc822(open('message.eml').read()) ``` -------------------------------- ### Create HTML Email Message Source: https://github.com/lavr/python-emails/blob/master/docs/examples.rst Instantiate an HTML email message with a subject, HTML content, and sender address. Requires the 'emails' library. ```python import emails message = emails.html(html=open('letter.html'), subject='Friday party', mail_from=('Company Team', 'contact@mycompany.com')) ``` -------------------------------- ### emails.loader.from_zip Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Creates a message from a ZIP archive containing HTML and resources. ```APIDOC ## emails.loader.from_zip ### Description Create a message from a ZIP archive containing HTML and resources. ### Method POST ### Endpoint /emails/loader/from_zip ### Parameters #### Query Parameters - **zip_file** (string or file-like object) - Required - Path to ZIP file or a file-like object. - **loader_cls** (object) - Optional - Custom loader class. - **kwargs** (object) - Optional - Additional options (`html_filename`, `text_filename`, `message_params`). ### Response #### Success Response (200) - **Message** (object) - A Message instance. ### Request Example { "zip_file": "/path/to/archive.zip" } ### Response Example { "message_id": "fghij@example.com" } ``` -------------------------------- ### emails.html Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Convenience function that creates and returns a Message instance. Accepts all the same parameters as the Message constructor. ```APIDOC ## emails.html(**kwargs) ### Description Convenience function that creates and returns a [`Message`](#Message) instance. Accepts all the same parameters as the [`Message`](#Message) constructor. ### Request Example ```python msg = emails.html( html="

Hello!

", subject="Test", mail_from="sender@example.com" ) ``` ``` -------------------------------- ### Send Message with SMTP Configuration Source: https://github.com/lavr/python-emails/blob/master/docs/quickstart.md Sends a prepared email message using specified SMTP server details. The smtp dictionary configures host, port, authentication, and security. ```python response = message.send( to="recipient@example.com", smtp={ "host": "smtp.example.com", "port": 587, "tls": True, "user": "me@example.com", "password": "secret" } ) ``` -------------------------------- ### Enable SMTP Protocol Trace Source: https://github.com/lavr/python-emails/blob/master/docs/faq.md Set `debug=1` in the `smtp` dictionary to print the full SMTP conversation to stdout. This is useful for diagnosing authentication, TLS, or recipient rejection issues. ```python response = message.send( to="user@example.com", smtp={"host": "smtp.example.com", "port": 587, "tls": True, "user": "me", "password": "secret", "debug": 1} ) ``` -------------------------------- ### Configure DKIM Signing Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Use `Message.dkim()` to configure DKIM signing for your emails. The signature is applied when the message is serialized. Ensure you have your private key, domain, and selector. ```python msg.dkim(key=open("private.pem"), domain="example.com", selector="default") ``` -------------------------------- ### emails.loader.from_directory Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Creates a message from a local directory containing an HTML file and any referenced images or attachments. ```APIDOC ## emails.loader.from_directory ### Description Create a message from a local directory. The directory should contain an HTML file and any referenced images or attachments. ### Method POST ### Endpoint /emails/loader/from_directory ### Parameters #### Query Parameters - **directory** (string) - Required - Path to the directory. - **loader_cls** (object) - Optional - Custom loader class. - **kwargs** (object) - Optional - Additional options (`html_filename`, `text_filename`, `message_params`). ### Response #### Success Response (200) - **Message** (object) - A Message instance. ### Request Example { "directory": "/path/to/email/content" } ### Response Example { "message_id": "abcde@example.com" } ``` -------------------------------- ### emails.loader.from_file Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Creates a message from a single HTML file. ```APIDOC ## emails.loader.from_file ### Description Create a message from a single HTML file. ### Method GET ### Endpoint /emails/loader/from_file ### Parameters #### Query Parameters - **filename** (string) - Required - Path to the HTML file. - **kwargs** (object) - Optional - Additional options (`message_params`). ### Response #### Success Response (200) - **Message** (object) - A Message instance. ### Request Example { "filename": "/path/to/email.html" } ### Response Example { "message_id": "klmno@example.com" } ``` -------------------------------- ### Configure Python Logging Source: https://github.com/lavr/python-emails/blob/master/docs/faq.md Enable Python's standard `logging` module to view connection events and retries. You can configure the root logger or specific library loggers for detailed insights. ```python import logging logging.basicConfig(level=logging.DEBUG) ``` ```python # Or enable only the emails loggers: logging.getLogger("emails.backend.smtp.backend").setLevel(logging.DEBUG) logging.getLogger("emails.backend.smtp.client").setLevel(logging.DEBUG) ``` -------------------------------- ### Create HTML Message with Jinja2 Template Source: https://github.com/lavr/python-emails/blob/master/docs/quickstart.md Use JinjaTemplate for dynamic email content in the subject and HTML body. Requires the 'jinja2' package. ```python from emails.template import JinjaTemplate as T message = emails.html( subject=T("Payment Receipt No.{{ bill_no }}"), html=T("

Dear {{ name }},

Your payment of ${{ amount }} was received.

"), mail_from=("Billing", "billing@mycompany.com") ) ``` -------------------------------- ### Setting Reply-To, CC, and BCC Recipients Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Configure Reply-To, CC, and BCC recipients using various formats including strings, (name, email) tuples, or lists of either. CC recipients are visible to all, while BCC recipients are hidden. ```python message = emails.html( html="

Hello!

", subject="Team update", mail_from=("Alice", "alice@example.com"), mail_to=[("Bob", "bob@example.com"), ("Carol", "carol@example.com")], cc="dave@example.com", bcc=["eve@example.com", "frank@example.com"], reply_to=("Alice", "alice-reply@example.com") ) ``` -------------------------------- ### Load Email from Single File Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Load an email template from a single HTML file. Images and CSS are resolved relative to the file's directory. ```python message = emails.loader.from_file("/path/to/email-template/welcome.html") ``` -------------------------------- ### emails.loader.from_url Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Creates a message by downloading an HTML page from a URL. Images and stylesheets are fetched and embedded. ```APIDOC ## emails.loader.from_url ### Description Create a message by downloading an HTML page from a URL. Images and stylesheets are fetched and embedded. ### Method GET ### Endpoint /emails/loader/from_url ### Parameters #### Query Parameters - **url** (string) - Required - URL of the HTML page. - **requests_params** (object) - Optional - Parameters passed to HTTP requests. - **kwargs** (object) - Optional - Additional transformer options. ### Response #### Success Response (200) - **Message** (object) - A Message instance. ### Request Example { "url": "http://example.com" } ### Response Example { "message_id": "67890@example.com" } ``` -------------------------------- ### Send multiple emails asynchronously using a shared backend Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Efficiently send multiple emails by establishing a single asynchronous SMTP backend connection and reusing it across sends. ```python from emails.backend.smtp.aio_backend import AsyncSMTPBackend async with AsyncSMTPBackend(host="smtp.example.com", port=587, tls=True, user="login", password="secret") as backend: for msg in messages: await msg.send_async(smtp=backend) ``` -------------------------------- ### Message Class Constructor Source: https://github.com/lavr/python-emails/blob/master/docs/api.md The Message class is the primary entry point for constructing email messages. It accepts various parameters to define the email's content, recipients, and headers. ```APIDOC ## class Message(**kwargs) ### Description Create a new email message. ### Parameters * **html** (*str* *or* *None*) – HTML body content (string or file-like object). * **text** (*str* *or* *None*) – Plain text body content (string or file-like object). * **subject** (*str* *or* *None*) – Email subject line. Supports template rendering. * **mail_from** (*str* *or* *tuple* *or* *None*) – Sender address. Accepts a string "user@example.com" or a tuple ("Display Name", "user@example.com"). * **mail_to** (*str* *or* *tuple* *or* *list* *or* *None*) – Recipient address(es). Accepts a string, tuple, or list of strings/tuples. * **cc** (*str* *or* *tuple* *or* *list* *or* *None*) – CC recipient(s). Same format as `mail_to`. * **bcc** (*str* *or* *tuple* *or* *list* *or* *None*) – BCC recipient(s). Same format as `mail_to`. * **reply_to** (*str* *or* *tuple* *or* *list* *or* *None*) – Reply-To address(es). Same format as `mail_to`. * **headers** (*dict* *or* *None*) – Custom email headers as a dictionary. * **headers_encoding** (*str* *or* *None*) – Encoding for email headers (default: `'ascii'`). * **attachments** (*list* *or* *None*) – List of attachments (dicts or `BaseFile` objects). * **charset** (*str* *or* *None*) – Message character set (default: `'utf-8'`). * **message_id** (str or [`MessageID`](#emails.utils.MessageID) or bool or None) – Message-ID header value. Can be a string, a `MessageID` instance, `False` to omit, or `None` to auto-generate. * **date** (*str* *or* *datetime* *or* *float* *or* *bool* *or* *callable* *or* *None*) – Date header value. Accepts a string, `datetime`, float (timestamp), `False` to omit, or a callable that returns one of these types. ### Request Example ```python import emails msg = emails.Message( html="

Hello, World!

", subject="Test Email", mail_from=("Sender", "sender@example.com"), mail_to="recipient@example.com" ) ``` ``` -------------------------------- ### Chain DKIM Signing with Message Creation Source: https://github.com/lavr/python-emails/blob/master/docs/quickstart.md DKIM signing can be chained directly after message creation for a more concise syntax. ```python message = emails.html( html="

Signed message

", mail_from="sender@mycompany.com", subject="DKIM Test" ).dkim(key=open("private.pem", "rb"), domain="mycompany.com", selector="default") ``` -------------------------------- ### JinjaTemplate Class Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Use JinjaTemplate for emails with Jinja2 syntax. It allows dynamic content insertion using variables within the template string. ```APIDOC ## JinjaTemplate(template_text, environment=None) ### Description Template using [Jinja2](https://jinja.palletsprojects.com/) syntax. ### Parameters * **template_text** (string) - Jinja2 template string. * **environment** (jinja2.Environment) - Optional `jinja2.Environment` instance. ### Example ```python from emails.template import JinjaTemplate msg = emails.Message( html=JinjaTemplate("

Hello {{ name }}!

"), subject=JinjaTemplate("Welcome, {{ name }}"), mail_from="noreply@example.com" ) msg.send(render={"name": "Alice"}, smtp={"host": "localhost"}) ``` ``` -------------------------------- ### Load Email from ZIP Archive Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Read an HTML file and its associated resources from a ZIP archive. The archive must contain at least one .html file. Message parameters can be specified during loading. ```python message = emails.loader.from_zip( open("template.zip", "rb"), message_params={"subject": "Newsletter", "mail_from": "news@example.com"} ) ``` -------------------------------- ### Load Email from URL Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Fetch an HTML page from a URL and automatically embed referenced images and stylesheets. Allows passing parameters to the underlying HTTP requests. ```python import emails.loader message = emails.loader.from_url( url="https://example.com/newsletter/2024-01/index.html", requests_params={"timeout": 30} ) ``` -------------------------------- ### Send HTML Email with SMTP Source: https://github.com/lavr/python-emails/blob/master/docs/index.md Use this snippet to construct and send an HTML email. Specify the subject, HTML content, sender's email address, and SMTP server details for sending. Ensure your SMTP server configuration is correct. ```python import emails message = emails.html( subject="Hi from python-emails!", html="

Hello, World!

", mail_from=("Alice", "alice@example.com"), ) response = message.send( to="bob@example.com", smtp={"host": "smtp.example.com", "port": 587, "tls": True}, ) assert response.status_code == 250 ``` -------------------------------- ### Manage SMTP Connections Explicitly with SMTPBackend Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md For explicit control over SMTP connections, instantiate `SMTPBackend` and use it as a context manager. The connection is automatically closed upon exiting the `with` block. ```python from emails.backend.smtp import SMTPBackend with SMTPBackend(host="smtp.example.com", port=587, tls=True, user="me", password="secret") as backend: for recipient in recipients: message.send(to=recipient, smtp=backend) # Connection is closed automatically ``` -------------------------------- ### Load and Inline Images in HTML Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Embed images referenced in the HTML as inline attachments using `cid:` references by setting `images_inline=True` during transformation. This requires `load_images` to be enabled. ```python message = emails.Message( html='' ) message.transform(load_images=True, images_inline=True) ``` -------------------------------- ### Message.as_string Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Returns the message as a string, including DKIM signature if configured. ```APIDOC ## Message.as_string(message_cls=None) ### Description Return the message as a string, including DKIM signature if configured. ### Parameters #### Keyword Arguments - **message_cls** – Optional custom MIME message class. ### Returns Message as a string. ### Return type str ``` -------------------------------- ### Load Message from Zip Archive Source: https://github.com/lavr/python-emails/blob/master/docs/transformations.md Load message content from a zip file. The zip archive must contain at least one file with an '.html' extension. ```python message = emails.loader.from_zip(open('design_pack.zip', 'rb')) ``` -------------------------------- ### Enable SMTP Debugging Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Enable verbose debugging of the SMTP protocol conversation by setting `debug=1`. This prints the full interaction with the server to stdout. ```python message.send(smtp={"host": "smtp.example.com", "debug": 1}) ``` -------------------------------- ### Send Email via SMTP Provider Source: https://github.com/lavr/python-emails/blob/master/docs/faq.md Configure SMTP host, port, and credentials to send emails through providers like Gmail, Yandex, or Outlook. Ensure you use an app password if required by the provider. ```python response = message.send( to="recipient@example.com", smtp={ "host": "", "port": 587, "tls": True, "user": "your-email@example.com", "password": "your-password-or-app-password" } ) ``` -------------------------------- ### Attach Files and Inline Images Source: https://github.com/lavr/python-emails/blob/master/docs/examples.rst Add attachments to an email message, including files and inline images. Ensure files are opened in binary read mode ('rb'). ```python message.attach(data=open('event.ics', 'rb'), filename='Event.ics') message.attach(data=open('image.png', 'rb'), filename='image.png', content_disposition='inline') ``` -------------------------------- ### Manually Make Images Inline Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Mark individual attachments as inline and synchronize HTML references to use Content-ID (CID) URIs. This ensures images are displayed directly within the email body. ```python message = emails.Message(html='') message.attach(filename="promo.png", data=open("promo.png", "rb")) message.attachments["promo.png"].is_inline = True message.transformer.synchronize_inline_images() message.transformer.save() print(message.html) ``` -------------------------------- ### Send email asynchronously via SMTP Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Utilize send_async for non-blocking email transmission. Requires 'aiosmtplib' and supports both dictionary-based and backend instance configurations for SMTP. ```python response = await msg.send_async( to="user@example.com", smtp={"host": "smtp.example.com", "port": 587, "tls": True, "user": "login", "password": "secret"} ) ``` -------------------------------- ### StringTemplate Class Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Use StringTemplate for emails with Python's built-in string.Template syntax. It supports $variable or ${variable} placeholders. ```APIDOC ## StringTemplate(template_text, safe_substitute=True) ### Description Template using Python’s `string.Template` syntax (`$variable` or `${variable}`). ### Parameters * **template_text** (string) - Template string. * **safe_substitute** (boolean) - If `True` (default), undefined variables are left as-is. If `False`, undefined variables raise `KeyError`. ### Example ```python from emails.template import StringTemplate msg = emails.Message( html=StringTemplate("

Hello $name!

"), mail_from="noreply@example.com" ) ``` ``` -------------------------------- ### Load Email from RFC 822 (.eml) File Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Parse an RFC 822 formatted email, such as a .eml file. Set parse_headers=True to copy email headers like Subject, From, and To. ```python message = emails.loader.from_rfc822( open("archived.eml", "rb").read(), parse_headers=True ) ``` -------------------------------- ### Send Templated Message with Render Variables Source: https://github.com/lavr/python-emails/blob/master/docs/quickstart.md Pass template variables to the send() method using the 'render' parameter. Configure SMTP settings within the 'smtp' parameter. ```python message.send( to="customer@example.com", render={"name": "Alice", "bill_no": "12345", "amount": "99.00"}, smtp={"host": "smtp.example.com", "port": 587, "tls": True, "user": "billing", "password": "secret"} ) ``` -------------------------------- ### Message.as_message Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Returns the underlying MIME message object. ```APIDOC ## Message.as_message(message_cls=None) ### Description Return the underlying MIME message object. ### Parameters #### Keyword Arguments - **message_cls** – Optional custom MIME message class. ### Returns MIME message object. ``` -------------------------------- ### Sign Message with DKIM Source: https://github.com/lavr/python-emails/blob/master/docs/quickstart.md Apply DKIM signature to a message using a private key file, domain, and selector. The signature is applied automatically on send or serialization. ```python message.dkim( key=open("private.pem", "rb"), domain="mycompany.com", selector="default" ) ``` -------------------------------- ### Send HTML Email with Attachment Source: https://github.com/lavr/python-emails/blob/master/docs/quickstart.md Composes and sends an HTML email with an attachment. Requires SMTP server details for sending. ```python import emails message = emails.html( html="

Hello, World!

", subject="My first email", mail_from=("Me", "me@example.com") ) response = message.send(to="you@example.com", smtp={"host": "smtp.example.com", "port": 587, "tls": True, "user": "me", "password": "secret"}) ``` -------------------------------- ### Sign Email with DKIM Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Sign outgoing emails using DKIM for authentication. Provide the private key, domain, and selector to the dkim() method. Errors during signing can be ignored. ```python import emails msg = emails.Message( html="

Signed message

", mail_from=("Sender", "sender@example.com"), subject="DKIM Test" ) msg.dkim( key=open("private.pem").read(), domain="example.com", selector="default" ) msg.send(to="recipient@example.com", smtp={"host": "localhost"}) ``` -------------------------------- ### emails.loader.from_rfc822 Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Creates a message from an RFC 822 email object, primarily for demonstration and testing. ```APIDOC ## emails.loader.from_rfc822 ### Description Create a message from an RFC 822 email object (e.g., from `email.message`). Primarily intended for demonstration and testing purposes. ### Method POST ### Endpoint /emails/loader/from_rfc822 ### Parameters #### Query Parameters - **msg** (object) - Required - An `email.message.Message` object. - **loader_cls** (object) - Optional - Custom loader class. - **message_params** (object) - Optional - Additional parameters for the Message constructor. - **parse_headers** (boolean) - Optional - If `True`, parse and transfer email headers. ### Response #### Success Response (200) - **Message** (object) - A Message instance. ### Request Example { "msg": { /* email.message.Message object */ }, "parse_headers": true } ### Response Example { "message_id": "pqrst@example.com" } ``` -------------------------------- ### Attach Files to Email Source: https://github.com/lavr/python-emails/blob/master/docs/faq.md Use the `attach()` method to include files in emails. The MIME type is auto-detected from the filename, but can be specified explicitly. Supports both file paths and in-memory data. ```python # Attach a PDF message.attach(filename="report.pdf", data=open("report.pdf", "rb")) ``` ```python # Attach an Excel file message.attach(filename="data.xlsx", data=open("data.xlsx", "rb")) ``` ```python # Attach with an explicit MIME type message.attach( filename="archive.7z", data=open("archive.7z", "rb"), mime_type="application/x-7z-compressed" ) ``` ```python import io csv_data = "name,score\nAlice,95\nBob,87\n" message.attach( filename="scores.csv", data=io.BytesIO(csv_data.encode("utf-8")) ) ``` -------------------------------- ### Inspect Raw RFC 822 Message Output Source: https://github.com/lavr/python-emails/blob/master/docs/faq.md Use `message.as_string()` to view the raw RFC 822 output before sending. This is helpful for verifying MIME structure, headers, and content encoding, especially for attachments and inline images. ```python print(message.as_string()) ``` -------------------------------- ### Create HTML Message Source: https://github.com/lavr/python-emails/blob/master/docs/quickstart.md Creates an HTML email message using emails.html(). Specify HTML content, subject, and sender. ```python import emails message = emails.html( html="

Friday party!

You are invited.

", subject="Friday party", mail_from=("Company Team", "contact@mycompany.com") ) ``` -------------------------------- ### Message.render Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Sets template rendering data for the message. Template variables are substituted when accessing html_body, text_body, or subject. ```APIDOC ## Message.render(**kwargs) ### Description Set template rendering data. Template variables are substituted when accessing `html_body`, `text_body`, or `subject`. ### Parameters #### Keyword Arguments - **kwargs** – Key-value pairs used as template context. ### Request Example ```python msg = emails.Message( html=emails.template.JinjaTemplate("

Hello {{ name }}

"), subject=emails.template.JinjaTemplate("Welcome, {{ name }}") ) msg.render(name="World") ``` ``` -------------------------------- ### Custom Image Loading Logic Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Define a callable to control which images are loaded by the email transformer. This is useful for skipping specific images like tracking pixels. ```python def should_load(element, hints=None, **kwargs): # Skip tracking pixels src = element.attrib.get("src", "") if "track" in src or "pixel" in src: return False return True message.transform(load_images=should_load) ``` -------------------------------- ### Send email via SMTP Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Use the send method to dispatch an email through an SMTP server. Allows overriding recipients and sender, and provides SMTP connection details. ```python response = msg.send( to="user@example.com", smtp={"host": "smtp.example.com", "port": 587, "tls": True, "user": "login", "password": "secret"} ) ``` -------------------------------- ### Send Email via Django Email Backend Source: https://github.com/lavr/python-emails/blob/master/docs/examples.rst Utilize the DjangoMessage helper to send emails using the configured Django email backend. Requires Django integration. ```python from emails.django import DjangoMessage as Message message = Message(...) message.send(mail_to=('John Brown', 'jbrown@gmail.com'), context={'name': 'John'}) ``` -------------------------------- ### Message.dkim Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Configures DKIM signing for the message. The signature is applied when the message is serialized. ```APIDOC ## Message.dkim(key, domain, selector, ignore_sign_errors=False, **kwargs) ### Description Configure DKIM signing for the message. The signature is applied when the message is serialized via [`as_string()`](#Message.as_string), [`as_bytes()`](#Message.as_bytes), or [`send()`](#Message.send). This method is also available as `sign()`. ### Parameters #### Path Parameters - **key** – Private key for signing (PEM format). String, bytes, or file-like object. - **domain** – DKIM domain (e.g., `"example.com"`). - **selector** – DKIM selector (e.g., `"default"`). - **ignore_sign_errors** – If `True`, suppress signing exceptions. ### Returns The message instance (for chaining). ### Return type [Message](#Message) ### Request Example ```python msg.dkim(key=open("private.pem"), domain="example.com", selector="default") ``` ``` -------------------------------- ### Reuse SMTP Connections with Identical Configurations Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md When sending multiple emails with the same SMTP configuration, the library automatically reuses the underlying SMTP connection through an internal pool for efficiency. ```python smtp_config = {"host": "smtp.example.com", "port": 587, "tls": True, "user": "me", "password": "secret"} # These two calls reuse the same underlying SMTP connection message.send(to="alice@example.com", smtp=smtp_config) message.send(to="bob@example.com", smtp=smtp_config) ``` -------------------------------- ### Transform Image URLs with a Callable Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Apply a function to all image references (src attributes, background attributes, CSS url() values) to modify their URLs. The callback receives the current URL and the lxml element. ```python message = emails.Message(html='') message.transformer.apply_to_images( func=lambda src, **kw: "https://cdn.example.com/images/" + src ) message.transformer.save() print(message.html) ``` -------------------------------- ### Adding Custom Email Headers Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Include custom headers in your email by passing a dictionary to the 'headers' parameter. Non-ASCII characters in header values are automatically encoded. ```python message = emails.html( html="

Hello!

", subject="Test", mail_from="sender@example.com", headers={ "X-Mailer": "python-emails", "X-Priority": "1", "List-Unsubscribe": "" } ) ``` -------------------------------- ### Django Integration with Custom Connection Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Send emails using a custom Django email backend connection. This allows for specific configurations like using an SMTP backend. ```python from django.core.mail import get_connection from emails.django import DjangoMessage message = DjangoMessage( html="

Notification

", subject="Alert", mail_from="alerts@example.com" ) connection = get_connection(backend="django.core.mail.backends.smtp.EmailBackend") message.send(to="admin@example.com", connection=connection) ``` -------------------------------- ### Add DKIM Signature to Email Source: https://github.com/lavr/python-emails/blob/master/docs/examples.rst Sign an email message with a DKIM signature. Requires a private key file, domain, and selector. ```python message.dkim(key=open('my.key'), domain='mycompany.com', selector='newsletter') ``` -------------------------------- ### emails.loader.from_html Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Creates a message from an HTML string. It can automatically load and embed images and stylesheets referenced in the HTML. ```APIDOC ## emails.loader.from_html ### Description Create a message from an HTML string. Images and stylesheets referenced in the HTML can be automatically loaded and embedded. ### Method POST ### Endpoint /emails/loader/from_html ### Parameters #### Query Parameters - **html** (string) - Required - HTML content as a string. - **text** (string) - Optional - Plain text alternative. - **base_url** (string) - Optional - Base URL for resolving relative URLs in the HTML. - **message_params** (object) - Optional - Additional parameters passed to the Message constructor. - **local_loader** (object) - Optional - A loader instance for resolving local file references. - **template_cls** (object) - Optional - Template class to use for the HTML body. - **message_cls** (object) - Optional - Custom Message class to instantiate. - **source_filename** (string) - Optional - Filename hint for the source HTML. - **requests_params** (object) - Optional - Parameters passed to HTTP requests when fetching resources. - **kwargs** (object) - Optional - Additional transformer options. ### Response #### Success Response (200) - **Message** (object) - A Message instance. ### Request Example { "html": "

Hello

", "text": "Hello" } ### Response Example { "message_id": "12345@example.com" } ``` -------------------------------- ### Add File Attachment Source: https://github.com/lavr/python-emails/blob/master/docs/quickstart.md Attaches a file to an email message. The filename and data are required. By default, attachments have content_disposition='attachment'. ```python message.attach(filename="report.pdf", data=open("report.pdf", "rb")) message.attach(filename="data.csv", data=open("data.csv", "rb")) ``` -------------------------------- ### Render Message with Template Data Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Use `Message.render()` to substitute template variables in the HTML body, text body, or subject. This is useful when your email content includes dynamic data. ```python msg = emails.Message( html=emails.template.JinjaTemplate("

Hello {{ name }}

"), subject=emails.template.JinjaTemplate("Welcome, {{ name }}") ) msg.render(name="World") ``` -------------------------------- ### Message.attach Source: https://github.com/lavr/python-emails/blob/master/docs/api.md Attaches a file to the email message. Supports specifying filename, data, content disposition, and MIME type. ```APIDOC ## Message.attach(**kwargs) ### Description Attach a file to the message. Sets `content_disposition` to `'attachment'` by default. ### Parameters * **filename** – Name of the attached file. * **data** – File content as bytes or a file-like object. * **content_disposition** – `'attachment'` (default) or `'inline'`. * **mime_type** – MIME type of the file. Auto-detected from filename if not specified. ### Request Example ```python msg.attach(filename="report.pdf", data=open("report.pdf", "rb")) msg.attach(filename="logo.png", data=img_data, content_disposition="inline") ``` ``` -------------------------------- ### Internationalized Domain Names (IDN) Email Addresses Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Send emails to addresses with internationalized domain names. The library automatically handles the necessary encoding for these addresses. ```python message = emails.html( html="

Hello!

", mail_from=("Sender", "user@example.com"), mail_to=("Recipient", "user@example.com") ) ``` -------------------------------- ### Transform HTML Body with Default Settings Source: https://github.com/lavr/python-emails/blob/master/docs/advanced.md Process the HTML body of an email message using the `transform()` method. By default, it inlines CSS, removes unsafe tags, and sets the content type meta tag. ```python message = emails.Message( html="

Hello!

" ) message.transform() ```