Merge pull request #918 from simple-login/handle-error-as-bytes

handle the AttributeError that can also be raised by as_bytes()
This commit is contained in:
Son Nguyen Kim 2022-04-22 10:51:55 +02:00 committed by GitHub
commit 5053d9f1f5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 21 deletions

View file

@ -6,7 +6,9 @@ extend-ignore =
E203, E203,
E501, E501,
# Ignore "f-string is missing placeholders" # Ignore "f-string is missing placeholders"
F541 F541,
# allow bare except
E722, B001
exclude = exclude =
.git, .git,
__pycache__, __pycache__,

View file

@ -8,9 +8,6 @@ import random
import time import time
import uuid import uuid
from copy import deepcopy from copy import deepcopy
from aiosmtpd.smtp import Envelope
from email import policy, message_from_bytes, message_from_string from email import policy, message_from_bytes, message_from_string
from email.header import decode_header, Header from email.header import decode_header, Header
from email.message import Message, EmailMessage from email.message import Message, EmailMessage
@ -25,6 +22,7 @@ import dkim
import newrelic.agent import newrelic.agent
import re2 as re import re2 as re
import spf import spf
from aiosmtpd.smtp import Envelope
from cachetools import cached, TTLCache from cachetools import cached, TTLCache
from email_validator import ( from email_validator import (
validate_email, validate_email,
@ -843,24 +841,19 @@ def copy(msg: Message) -> Message:
def to_bytes(msg: Message): def to_bytes(msg: Message):
"""replace Message.as_bytes() method by trying different policies""" """replace Message.as_bytes() method by trying different policies"""
try: for generator_policy in [None, policy.SMTP, policy.SMTPUTF8]:
return msg.as_bytes()
except UnicodeEncodeError:
LOG.w("as_bytes fails with default policy, try SMTP policy")
try: try:
return msg.as_bytes(policy=policy.SMTP) return msg.as_bytes(policy=generator_policy)
except UnicodeEncodeError: except:
LOG.w("as_bytes fails with SMTP policy, try SMTPUTF8 policy") LOG.w("as_bytes() fails with %s policy", policy, exc_info=True)
try:
return msg.as_bytes(policy=policy.SMTPUTF8) msg_string = msg.as_string()
except UnicodeEncodeError: try:
LOG.w("as_bytes fails with SMTPUTF8 policy, try converting to string") return msg_string.encode()
msg_string = msg.as_string() except:
try: LOG.w("as_string().encode() fails", exc_info=True)
return msg_string.encode()
except UnicodeEncodeError as e: return msg_string.encode(errors="replace")
LOG.w("can't encode msg, err:%s", e)
return msg_string.encode(errors="replace")
def should_add_dkim_signature(domain: str) -> bool: def should_add_dkim_signature(domain: str) -> bool: