mirror of
https://github.com/simple-login/app.git
synced 2024-09-20 15:05:59 +08:00
add get_encoding() and encode_text()
This commit is contained in:
parent
da8b0089ff
commit
e2a7061429
|
@ -1,5 +1,7 @@
|
|||
import base64
|
||||
import email
|
||||
import os
|
||||
import quopri
|
||||
import random
|
||||
import re
|
||||
from email.header import decode_header
|
||||
|
@ -671,6 +673,33 @@ def is_valid_email(email_address: str) -> bool:
|
|||
)
|
||||
|
||||
|
||||
def get_encoding(msg: Message) -> str:
|
||||
"""
|
||||
Return the message encoding, possible values:
|
||||
- quoted-printable
|
||||
- base64: default if unknown
|
||||
"""
|
||||
cte = str(msg.get("content-transfer-encoding", "")).lower()
|
||||
if cte == "":
|
||||
return "base64"
|
||||
|
||||
if cte == "quoted-printable" or cte == "base64":
|
||||
return cte
|
||||
|
||||
LOG.exception("Unknown encoding %s", cte)
|
||||
|
||||
return "base64"
|
||||
|
||||
|
||||
def encode_text(text: str, encoding: str = "base64") -> str:
|
||||
if encoding == "quoted-printable":
|
||||
encoded = quopri.encodestring(text.encode("utf-8"))
|
||||
return str(encoded, "utf-8")
|
||||
else: # use base64 by default
|
||||
encoded = base64.b64encode(text.encode("utf-8"))
|
||||
return str(encoded, "utf-8")
|
||||
|
||||
|
||||
def add_header(msg: Message, text_header, html_header) -> Message:
|
||||
if msg.get_content_type() == "text/plain":
|
||||
payload = msg.get_payload()
|
||||
|
|
|
@ -18,6 +18,8 @@ from app.email_utils import (
|
|||
to_bytes,
|
||||
generate_reply_email,
|
||||
normalize_reply_email,
|
||||
get_encoding,
|
||||
encode_text,
|
||||
)
|
||||
from app.extensions import db
|
||||
from app.models import User, CustomDomain
|
||||
|
@ -416,3 +418,23 @@ def test_generate_reply_email(flask_client):
|
|||
def test_normalize_reply_email(flask_client):
|
||||
assert normalize_reply_email("re+abcd@sl.local") == "re+abcd@sl.local"
|
||||
assert normalize_reply_email('re+"ab cd"@sl.local') == "re+_ab_cd_@sl.local"
|
||||
|
||||
|
||||
def test_get_encoding():
|
||||
msg = email.message_from_string("")
|
||||
assert get_encoding(msg) == "base64"
|
||||
|
||||
msg = email.message_from_string("Content-TRANSFER-encoding: Invalid")
|
||||
assert get_encoding(msg) == "base64"
|
||||
|
||||
msg = email.message_from_string("Content-TRANSFER-encoding: quoted-printable")
|
||||
assert get_encoding(msg) == "quoted-printable"
|
||||
|
||||
|
||||
def test_encode_text():
|
||||
assert encode_text("") == ""
|
||||
assert encode_text("ascii") == "YXNjaWk="
|
||||
assert encode_text("ascii", "quoted-printable") == "ascii"
|
||||
|
||||
assert encode_text("mèo méo") == "bcOobyBtw6lv"
|
||||
assert encode_text("mèo méo", "quoted-printable") == "m=C3=A8o m=C3=A9o"
|
||||
|
|
Loading…
Reference in a new issue