use deepcopy instead of email.message_from_string in copy()

This commit is contained in:
Son Nguyen Kim 2021-08-20 16:03:22 +02:00
parent 51578ce934
commit 76c1b3d807
1 changed files with 9 additions and 5 deletions

View File

@ -14,6 +14,7 @@ from email.mime.text import MIMEText
from email.utils import make_msgid, formatdate, parseaddr from email.utils import make_msgid, formatdate, parseaddr
from smtplib import SMTP, SMTPServerDisconnected from smtplib import SMTP, SMTPServerDisconnected
from typing import Tuple, List, Optional from typing import Tuple, List, Optional
from copy import deepcopy
import arrow import arrow
import dkim import dkim
@ -697,11 +698,14 @@ def parseaddr_unicode(addr) -> (str, str):
def copy(msg: Message) -> Message: def copy(msg: Message) -> Message:
"""return a copy of message""" """return a copy of message"""
try: try:
# prefer the unicode way return deepcopy(msg)
return email.message_from_string(msg.as_string()) except:
except (UnicodeEncodeError, KeyError, LookupError): LOG.warning("deepcopy fails, try string parsing")
LOG.warning("as_string() fails, try to_bytes") try:
return email.message_from_bytes(to_bytes(msg)) return email.message_from_string(msg.as_string())
except (UnicodeEncodeError, KeyError, LookupError):
LOG.warning("as_string() fails, try bytes parsing")
return email.message_from_bytes(to_bytes(msg))
def to_bytes(msg: Message): def to_bytes(msg: Message):