~homeworkprod/byceps

ref: 9f9e7abd1a07b6d61a6f083d62fadb3eec563900 byceps/byceps/email.py -rw-r--r-- 1.8 KiB
9f9e7abd — Jochen Kupperschmidt Rework retrieval of user's orga team to show on public profile 1 year, 9 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
"""
byceps.email
~~~~~~~~~~~~

Sending e-mail.

:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from typing import List, 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()