~homeworkprod/byceps

ref: bcef32cd2dc329bcf81057794883008f5c040ac8 byceps/byceps/email.py -rw-r--r-- 1.8 KiB
bcef32cd — Jochen Kupperschmidt Work around Jinja 3.0.0 bug with `for` inside of `set` block 5 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""
byceps.email
~~~~~~~~~~~~

Sending e-mail.

:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

from __future__ import annotations
from typing import Optional

from flask import current_app
from marrow.mailer import Mailer


def init_app(app):
    marrowmailer_config_key = 'MARROWMAILER_CONFIG'

    if marrowmailer_config_key not in app.config:
        app.config[marrowmailer_config_key] = _get_config(app)

    mailer_config = app.config.get(marrowmailer_config_key)

    app.marrowmailer = Mailer(mailer_config)


def _get_config(app):
    if app.config.get('MAIL_SUPPRESS_SEND', False) or app.testing:
        return {
            'transport.use': 'mock',
        }

    config = {
        'transport.use': 'smtp',
        'transport.host': app.config.get('MAIL_SERVER', 'localhost'),
        'transport.port': app.config.get('MAIL_PORT', 25),
        'transport.debug': app.config.get('MAIL_DEBUG', app.debug),
        'message.author': app.config.get('MAIL_DEFAULT_SENDER', None),
    }

    username = app.config.get('MAIL_USERNAME', None)
    if username is not None:
        config['transport.username'] = username

    password = app.config.get('MAIL_PASSWORD', None)
    if password is not None:
        config['transport.password'] = password

    if app.config.get('MAIL_USE_SSL', False):
        config['transport.tls'] = 'ssl'

    if app.config.get('MAIL_USE_TLS', False):
        config['transport.tls'] = 'required'

    return config


def send(
    sender: Optional[str], recipients: list[str], subject: str, body: str
) -> None:
    """Assemble and send an e-mail."""
    mailer = current_app.marrowmailer

    message = mailer.new(
        author=sender, to=recipients, subject=subject, plain=body, brand=False
    )

    mailer.start()
    mailer.send(message)
    mailer.stop()