Skip to main content

A simple email component for the Molten web framework

Project description

molten-mail

PyPI PyPI Build Status codecov

Provides a simple interface to set up SMTP with your Molten web application and send messages from your handler functions. Please note this work derives largely from the Flask-Mail extension by 'Dan Jacob' and contributors, but has been modified extensively to remove Python 2 support and be used as a Molten component.

Installation

pip install molten-mail

If you plan on using HTML templates you will need to ensure that Jinja2 is installed.

pip install molten-mail[templates]

Usage

Be sure to check the examples folder for sample applications and more complex usage.

Example Setup

To send mail messages from your view functions you must instantiate a Mail instance yourself or use the MailComponent. The MailComponent will instantiate a global Mail instance from settings provided in the molten.Settings.

Here we have a minimally viable app capable of sending an email message and returning a 204 response code:

from molten import (
    App,
    Route,
    Settings,
    SettingsComponent,
    QueryParams,
    HTTP_204,
    HTTP_400,
    Response,
)
from molten_mail import MailComponent, Mail, Message

# Replace with your own SMTP parameters
settings = Settings(
    {
        "MAIL_SERVER": "smtp.example.com",
        "MAIL_USERNAME": "me@example.com",
        "MAIL_PASSWORD": "dontaddthistoyourversioncontrol",
        "MAIL_PORT": 587,
        "MAIL_USE_TLS": True,
        "MAIL_DEFAULT_SENDER": "me@example.com",
    }
)


def send_message(params: QueryParams, mail: Mail):
    """Emails an email address provided in the query string"""
    addresses = params.get_all("email")
    if not addresses:
        return Response(
            HTTP_400,
            content="Provide emails in the query params to send a welcome message",
        )
    msg = Message(
        subject="Welcome to Molten!",
        body="Welcome to Molten! Glad to have you here.",
        recipients=addresses,
    )
    mail.send(msg)
    return Response(HTTP_204, content="")


routes = [Route("/", send_message, "POST")]

components = [SettingsComponent(settings), MailComponent()]

app = App(routes=routes, components=components)

Configuration Options

A singleton Mail component can be configured for use in dependency injection using options included in your molten.Settings. This requires that you include the MailComponent within you molten.App instance. The key values can either be all upper or lowercase and begin with MAIL_. The available options are:

  • 'MAIL_SERVER': default 'localhost'
  • 'MAIL_USERNAME': default None
  • 'MAIL_PASSWORD': default None
  • 'MAIL_PORT': default 25
  • 'MAIL_USE_TLS': default False
  • 'MAIL_USE_SSL': default False
  • 'MAIL_DEFAULT_SENDER': default None
  • 'MAIL_DEBUG': default False
  • 'MAIL_MAX_EMAILS': default None
  • 'MAIL_SUPPRESS_SEND': default False
  • 'MAIL_ASCII_ATTACHMENTS': False

Sending Messages

To send a message, instantiate a Mail component. Then create an instance of Message, and pass it to your Mail component using mail.send(msg)

from molten_mail import Mail, Message

mail = Mail(server="localhost",
            user="me@example.com",
            password="dontaddthistoyourversioncontrol",
            port=587,
            use_tls=True,
            default_sender="me@example.com")
msg = Message(subject="Hey there!", body="Welcome to Molten Mail", recipients=["you@example.com"])
mail.send(msg)

Your message recipients can be set in bulk or individually:

msg.recipients = ['you@example.com', 'me@example.com']
msg.add_recipient('otherperson@example.com')

If you have included a default sender you do not need to set the message sender explicitly, as it will use this configuration value by default:

msg = Message('Hello',
              recipients=['you@example.com'])

The sender can also be passed as a two element tuple containing a name and email address which will be split like so:

msg = Message('Hello',
              sender=('Me', 'me@example.com'))

assert msg.sender == 'Me <me@example.com>'

A Message can contain a body and/or HTML:

msg.body = 'message body'
msg.html = '<b>Hello Molten-mail!</b>'

A convenience function send_message can also be used to create and send a message:

mail.send_message(subject="Your subject", body="Message body", recipients=["you@example.com"])

HTML Email Templates

Molten-mail includes a convenience component MailTemplates for rendering HTML email bodies using Jinja2. You have to install jinja2 yourself before using this module.

You must include the MailTemplatesComponent in your app, passing the path to a folder containing your templates.

from molten import App, Route, Response, HTTP_204, Settings, SettingsComponent
from molten_mail import Mail, MailComponent
from molten_mail.templates import MailTemplates, MailTemplatesComponent

settings = Settings({
    ...
})

def view_func(mail: Mail, mail_templates: MailTemplates): -> Response:
    mail.send_message(
        subject="Hello Molten!",
        html=mail_templates.render("my_email_template.html", somevalue="Key values for the template context"),
        recipients=["you@example.com"]
    )
    return Response(HTTP_204, content="")

app = App(
    components=[SettingsComponent(settings),
                MailComponent(),
                MailTemplatesComponent('./path_to_templates_dir')],
    routes=[Route('/', view_func, method="POST"]
)

Testing

To run the test suite with coverage first install the package in editable mode with it's full testing requirements:

$ pip install -e ".[dev]"

To run the project's tests

$ pytest --cov

To run tests against multiple python interpreters use:

$ tox

HISTORY

0.1.0 Initial Release

  • Initial release.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

molten_mail-0.1.0.tar.gz (16.0 kB view details)

Uploaded Source

Built Distribution

molten_mail-0.1.0-py36-none-any.whl (10.6 kB view details)

Uploaded Python 3.6

File details

Details for the file molten_mail-0.1.0.tar.gz.

File metadata

  • Download URL: molten_mail-0.1.0.tar.gz
  • Upload date:
  • Size: 16.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.4.2 requests/2.20.0 setuptools/40.4.3 requests-toolbelt/0.8.0 tqdm/4.28.1 CPython/3.6.5

File hashes

Hashes for molten_mail-0.1.0.tar.gz
Algorithm Hash digest
SHA256 dd6a60a0fca288c4dcd90d24a98bb8014368ed2a5e8e148a0df36c792653719d
MD5 6d888f41d5445be413463e3144dd504c
BLAKE2b-256 f1d4305c4583eda6799c95835c4d1caf54c0adbb3d26af4894513e1244900af0

See more details on using hashes here.

File details

Details for the file molten_mail-0.1.0-py36-none-any.whl.

File metadata

  • Download URL: molten_mail-0.1.0-py36-none-any.whl
  • Upload date:
  • Size: 10.6 kB
  • Tags: Python 3.6
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.4.2 requests/2.20.0 setuptools/40.4.3 requests-toolbelt/0.8.0 tqdm/4.28.1 CPython/3.6.5

File hashes

Hashes for molten_mail-0.1.0-py36-none-any.whl
Algorithm Hash digest
SHA256 393bac634d14c98f2cd7d4018341317095f92bf3eb8bcbae996670781c85562f
MD5 984cd46849a56b2272c60e37e64d6d47
BLAKE2b-256 43e249ab3fb3e2a741e3522029435cf188c2095ffeec5735ccb58dbb90f40069

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page