This repository has been archived by the owner on Dec 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Handle badly declared charsets in message body
- Loading branch information
Showing
2 changed files
with
22 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -8,6 +8,7 @@ from sys import platform as _platform | |
from urllib.error import URLError, HTTPError | ||
from urllib.request import Request, urlopen | ||
import argparse | ||
import chardet | ||
import email | ||
import functools | ||
import html | ||
|
@@ -369,6 +370,14 @@ def handle_html_message_body(input_email, part): | |
charset = 'utf-8' | ||
logger.info("Determined email is HTML with charset " + str(charset)) | ||
|
||
try: | ||
payload_unicode = str(payload, charset) | ||
except UnicodeDecodeError: | ||
detection = chardet.detect(payload) | ||
charset = detection["encoding"] | ||
logger.info("Detected charset can't decode body; trying again with charset " + charset) | ||
payload_unicode = str(payload, charset) | ||
|
||
def cid_replace(cid_parts_used, matchobj): | ||
cid = matchobj.group(1) | ||
|
||
|
@@ -391,7 +400,7 @@ def handle_html_message_body(input_email, part): | |
return "broken" | ||
|
||
payload = re.sub(r'cid:([\[email protected]]+)', functools.partial(cid_replace, cid_parts_used), | ||
str(payload, charset)) | ||
payload_unicode) | ||
|
||
return (payload, cid_parts_used) | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters