| 1 |
""" |
| 2 |
flask_security.mail_util |
| 3 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 4 |
|
| 5 |
Utility class providing methods for validating, normalizing and sending emails. |
| 6 |
|
| 7 |
:copyright: (c) 2020-2025 by J. Christopher Wagner (jwag). |
| 8 |
:license: MIT, see LICENSE for more details. |
| 9 |
|
| 10 |
While this default implementation uses Flask-Mail - we want to make sure that |
| 11 |
Flask-Mailman isn't REQUIRED (if this implementation isn't used). |
| 12 |
""" |
| 13 |
|
| 14 |
from __future__ import annotations |
| 15 |
|
| 16 |
import typing as t |
| 17 |
|
| 18 |
import email_validator |
| 19 |
from flask import current_app |
| 20 |
|
| 21 |
from .utils import config_value, get_message |
| 22 |
|
| 23 |
if t.TYPE_CHECKING: # pragma: no cover |
| 24 |
import flask |
| 25 |
|
| 26 |
|
| 27 |
class EmailValidateException(ValueError): |
| 28 |
"""This is raised for any email validation errors. |
| 29 |
This can be used by custom MailUtil implementations to provide |
| 30 |
custom error messages. |
| 31 |
""" |
| 32 |
|
| 33 |
def __init__(self, message: str) -> None: |
| 34 |
super().__init__(message) |
| 35 |
self.msg = message |
| 36 |
|
| 37 |
|
| 38 |
class MailUtil: |
| 39 |
""" |
| 40 |
Utility class providing methods for validating, normalizing and sending emails. |
| 41 |
|
| 42 |
This default class uses the email_validator package to handle validation and |
| 43 |
normalization, and the flask_mailman package (if initialized) to send emails. |
| 44 |
|
| 45 |
To provide your own implementation, pass in the class as ``mail_util_cls`` |
| 46 |
at init time. Your class will be instantiated once as part of app initialization. |
| 47 |
|
| 48 |
.. versionadded:: 4.0.0 |
| 49 |
""" |
| 50 |
|
| 51 |
def __init__(self, app: flask.Flask): |
| 52 |
"""Instantiate class. |
| 53 |
|
| 54 |
:param app: The Flask application being initialized. |
| 55 |
""" |
| 56 |
pass |
| 57 |
|
| 58 |
def send_mail( |
| 59 |
self, |
| 60 |
template: str, |
| 61 |
subject: str, |
| 62 |
recipient: str, |
| 63 |
sender: str | tuple, |
| 64 |
body: str, |
| 65 |
html: str | None, |
| 66 |
**kwargs: t.Any, |
| 67 |
) -> None: |
| 68 |
"""Send an email via the Flask-Mailman or Flask-Mail or other mail extension. |
| 69 |
|
| 70 |
:param template: the Template name. The message has already been rendered |
| 71 |
however this might be useful to differentiate why the email is being sent. |
| 72 |
:param subject: Email subject |
| 73 |
:param recipient: Email recipient |
| 74 |
:param sender: who to send email as (see :py:data:`SECURITY_EMAIL_SENDER`) |
| 75 |
:param body: the rendered body (text) |
| 76 |
:param html: the rendered body (html) |
| 77 |
:param kwargs: the entire context |
| 78 |
|
| 79 |
It is possible that sender is a lazy_string for localization (unlikely but..) |
| 80 |
so we cast to str() here to force localization. |
| 81 |
""" |
| 82 |
|
| 83 |
if current_app.extensions.get("mailman", None): # pragma: no cover |
| 84 |
from flask_mailman import EmailMultiAlternatives, Mail |
| 85 |
|
| 86 |
# Flask-Mailman doesn't appear to take a tuple - a bug has been filed |
| 87 |
# but not sure they will fix it (parts of Flask-Mailman work - but not |
| 88 |
# the actual email headers). |
| 89 |
if isinstance(sender, tuple) and len(sender) == 2: |
| 90 |
# sender = (str(sender[0]), str(sender[1])) |
| 91 |
sender = f"{str(sender[0])} <{str(sender[1])}>" |
| 92 |
else: |
| 93 |
sender = str(sender) |
| 94 |
|
| 95 |
mail: Mail = current_app.extensions.get("mailman") |
| 96 |
with mail.get_connection() as connection: |
| 97 |
msg = EmailMultiAlternatives( |
| 98 |
subject, |
| 99 |
body=body, |
| 100 |
from_email=sender, |
| 101 |
to=[recipient], |
| 102 |
connection=connection, |
| 103 |
) |
| 104 |
if html: |
| 105 |
msg.attach_alternative(html, "text/html") |
| 106 |
msg.send() |
| 107 |
|
| 108 |
elif current_app.extensions.get("mail", None): |
| 109 |
from flask_mail import Message |
| 110 |
|
| 111 |
# In Flask-Mail, sender can be a two element tuple -- (name, address) |
| 112 |
if isinstance(sender, tuple) and len(sender) == 2: |
| 113 |
sender = (str(sender[0]), str(sender[1])) |
| 114 |
else: |
| 115 |
sender = str(sender) |
| 116 |
msg = Message(subject, sender=sender, recipients=[recipient]) |
| 117 |
msg.body = body |
| 118 |
msg.html = html |
| 119 |
|
| 120 |
mail = current_app.extensions.get("mail") |
| 121 |
mail.send(msg) # type: ignore |
| 122 |
|
| 123 |
else: # pragma: no cover |
| 124 |
raise ValueError("No email extension configured") |
| 125 |
|
| 126 |
def normalize(self, email: str) -> str: |
| 127 |
""" |
| 128 |
Given an input email - return a normalized version or |
| 129 |
raise EmailValidateException if field value isn't syntactically valid. |
| 130 |
|
| 131 |
This is called by forms that use email as an identity to be looked up. |
| 132 |
|
| 133 |
Must be called in app context and uses :py:data:`SECURITY_EMAIL_VALIDATOR_ARGS` |
| 134 |
config variable to pass any relevant arguments to |
| 135 |
email_validator.validate_email() method. |
| 136 |
|
| 137 |
This defaults to NOT checking for deliverability (i.e. DNS checks). |
| 138 |
""" |
| 139 |
validator_args = config_value("EMAIL_VALIDATOR_ARGS") or {} |
| 140 |
validator_args["check_deliverability"] = False |
| 141 |
try: |
| 142 |
valid = email_validator.validate_email(email, **validator_args) |
| 143 |
return valid.normalized |
| 144 |
except ValueError: |
| 145 |
raise EmailValidateException(get_message("INVALID_EMAIL_ADDRESS")[0]) |
| 146 |
|
| 147 |
def validate(self, email: str) -> str: |
| 148 |
""" |
| 149 |
Validate the given email. |
| 150 |
If valid, the normalized version is returned. |
| 151 |
This is used by forms/views that require an email that likely can have an |
| 152 |
actual email sent to it. |
| 153 |
|
| 154 |
Must be called in app context and uses :py:data:`SECURITY_EMAIL_VALIDATOR_ARGS` |
| 155 |
config variable to pass any relevant arguments to |
| 156 |
email_validator.validate_email() method. |
| 157 |
|
| 158 |
EmailValidationException is thrown on invalid email. |
| 159 |
""" |
| 160 |
|
| 161 |
validator_args = config_value("EMAIL_VALIDATOR_ARGS") or {} |
| 162 |
try: |
| 163 |
valid = email_validator.validate_email(email, **validator_args) |
| 164 |
return valid.normalized |
| 165 |
except ValueError: |
| 166 |
raise EmailValidateException(get_message("INVALID_EMAIL_ADDRESS")[0]) |