__all__ = [ 'MessageBase', ] import base64 import datetime import email.message import email.utils import enum import functools import html import json import logging import os import pathlib import re import subprocess import zipfile import bs4 import compressed_rtf import RTFDE import RTFDE.exceptions from email import policy from email.charset import Charset, QP from email.header import decode_header as _decode_header, Header as _Header from email.message import EmailMessage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.parser import HeaderParser from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Type, Union from .. import constants from .._rtf.create_doc import createDocument from .._rtf.inject_rtf import injectStartRTF from ..enums import ( BodyTypes, DeencapType, ErrorBehavior, RecipientType, SaveType ) from ..exceptions import ( ConversionError, DataNotFoundError, DeencapMalformedData, DeencapNotEncapsulated, IncompatibleOptionsError, MimetypeFailureError, WKError ) from .msg import MSGFile from ..structures.report_tag import ReportTag from ..recipient import Recipient from ..utils import ( addNumToDir, addNumToZipDir, createZipOpen, decodeRfc2047, findWk, htmlSanitize, inputToBytes, inputToString, isEncapsulatedRtf, prepareFilename, rtfSanitizeHtml, rtfSanitizePlain, stripRtf, validateHtml ) logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) _RFC2047_WORD = re.compile(r'=\?[^?]+\?[bBqQ]\?[^?]*\?=') # Encodings to try when a declared charset fails, keyed by normalised charset name. # GBK is a strict superset of GB2312 and accepts the ASCII-range second bytes that # GB2312 rejects, so real-world GB2312-labelled headers often decode correctly as GBK. _CHARSET_FALLBACKS: Dict[str, Tuple[str, ...]] = { 'gb2312': ('gbk', 'cp936'), 'gb_2312': ('gbk', 'cp936'), 'gb_2312-80': ('gbk', 'cp936'), } def _fix_encoded_word(m: re.Match) -> str: """ Regex substitution callback: decode one RFC 2047 encoded word and re-emit it as a valid UTF-8 encoded word. If the declared charset fails (e.g. GB2312-labelled GBK bytes), charset fallbacks from _CHARSET_FALLBACKS are tried before falling back to latin-1 with replacement characters. """ word = m.group(0) try: parts = _decode_header(word) if len(parts) != 1 or not isinstance(parts[0][0], bytes): return word btext, cs = parts[0] try: text = btext.decode(cs or 'ascii') except (UnicodeDecodeError, LookupError): for fallback in _CHARSET_FALLBACKS.get((cs or '').lower(), ()): try: text = btext.decode(fallback) break except (UnicodeDecodeError, LookupError): continue else: text = btext.decode('latin-1', 'replace') return str(_Header(text, charset='utf-8')) except Exception: return word def _preprocess_encoded_words(text: str) -> str: """ Replace every RFC 2047 encoded word in *text* with a clean UTF-8 encoded word. Safe to apply to an entire raw header block before feeding it to the modern email policy parser. """ return _RFC2047_WORD.sub(_fix_encoded_word, text) def _sanitize_header(value: str) -> str: """ Prepare a header value from a compat32-parsed Message for safe assignment to an EmailMessage (fallback path when no raw headerText is available). RFC 2047 encoded words are re-encoded as UTF-8; raw non-ASCII characters are also RFC 2047-encoded so that EmailMessage.as_bytes() never raises UnicodeEncodeError. """ if '=?' in value: value = _RFC2047_WORD.sub(_fix_encoded_word, value) try: value.encode('ascii') except (UnicodeEncodeError, UnicodeDecodeError): value = str(_Header(value, charset='utf-8')) return value class MessageBase(MSGFile): """ Base class for Message-like MSG files. """ def __init__(self, path, **kwargs): """ Supports all of the options from :meth:`MSGFile.__init__` with some additional ones. :param recipientSeparator: Optional, separator string to use between recipients. :param deencapsulationFunc: Optional, if specified must be a callable that will override the way that HTML/text is deencapsulated from the RTF body. This function must take exactly 2 arguments, the first being the RTF body from the message and the second being an instance of the enum ``DeencapType`` that will tell the function what type of body is desired. The function should return a string for plain text and bytes for HTML. If any problems occur, the function *must* either return ``None`` or raise one of the appropriate exceptions from :mod:`extract_msg.exceptions`. All other exceptions must be handled internally or they will not be caught. The original deencapsulation method will not run if this is set. """ super().__init__(path, **kwargs) # The rest needs to be in a try-except block to ensure the file closes # if an error occurs. try: self.__headerInit = False self.__recipientSeparator: str = kwargs.get('recipientSeparator', ';') self.__deencap = kwargs.get('deencapsulationFunc') self.header # This variable keeps track of what the new line character should be. self._crlf = '\n' try: self.body except Exception as e: # Prevent an error in the body from preventing opening. logger.exception('Critical error accessing the body. File opened but accessing the body will throw an exception.') self._htmlEncoding = None except: try: self.close() except: pass raise def _genRecipient(self, recipientStr: str, recipientType: RecipientType) -> Optional[str]: """ Method to generate the specified recipient field. """ value = None # Check header first. if self.headerInit: value = cast(Optional[str], self.header[recipientStr]) if value: value = decodeRfc2047(value) value = value.replace(',', self.__recipientSeparator) # If the header had a blank field or didn't have the field, generate # it manually. if not value: # Check if the header has initialized. if self.headerInit: logger.info(f'Header found, but "{recipientStr}" is not included. Will be generated from other streams.') # Get a list of the recipients of the specified type. foundRecipients = tuple(recipient.formatted for recipient in self.recipients if recipient.type is recipientType) # If we found recipients, join them with the recipient separator # and a space. if len(foundRecipients) > 0: value = (self.__recipientSeparator + ' ').join(foundRecipients) # Code to fix the formatting so it's all a single line. This allows # the user to format it themself if they want. This should probably # be redone to use re or something, but I can do that later. This # shouldn't be a huge problem for now. if value: value = value.replace(' \r\n\t', ' ').replace('\r\n\t ', ' ').replace('\r\n\t', ' ') value = value.replace('\r\n', ' ').replace('\r', ' ').replace('\n', ' ') while value.find(' ') != -1: value = value.replace(' ', ' ') return value def _getHtmlEncoding(self, soup: bs4.BeautifulSoup) -> None: """ Helper function to set the html encoding. """ if not self._htmlEncoding: try: self._htmlEncoding = cast(Optional[str], soup.original_encoding or soup.declared_html_encoding) except AttributeError: pass def asEmailMessage(self) -> EmailMessage: """ Returns an instance of EmailMessage used to represent the contents of this message. :raises ConversionError: The function failed to convert one of the attachments into a form that it could attach, and the attachment data type was not None. """ ret = EmailMessage() # Prefer the raw transport-header block: pre-fix any malformed RFC 2047 # encoded words (e.g. GB2312-labelled GBK bytes), then parse with the # modern policy so that RFC 5322 unfolding and RFC 2047 decoding are # handled natively and the values arrive as clean Unicode strings. # Fall back to the compat32-derived self.header when no raw text is # stored (synthesised headers from MAPI properties). _ADDRESS_HEADERS = frozenset({'to', 'cc', 'bcc', 'reply-to'}) if self.headerText: raw = self.headerText if raw.startswith('Microsoft Mail Internet Headers Version 2.0'): raw = raw[43:].lstrip() raw = _preprocess_encoded_words(raw) source_items = list(HeaderParser(policy = policy.default).parsestr(raw).items()) sanitize = False else: source_items = list(self.header.items()) sanitize = True # Address headers (To/CC/BCC/Reply-To) may appear once per recipient in # the stored header block; merge them into a single comma-separated value. # All other headers — including multi-valued trace headers like Received # and Authentication-Results — are forwarded as-is; EmailMessage appends # rather than replaces, so natural repetition is preserved correctly. address_merged: Dict[str, Tuple[str, str]] = {} for key, value in source_items: if key.lower() == 'content-type': continue if sanitize: # compat32 values are folded and may contain raw encoded words. value = re.sub(r'\r?\n[ \t]', ' ', value) value = value.replace('\r\n', '').replace('\n', '') value = _sanitize_header(value) lower = key.lower() if lower in _ADDRESS_HEADERS: if lower in address_merged: address_merged[lower] = (address_merged[lower][0], address_merged[lower][1] + ', ' + value) else: address_merged[lower] = (key, value) else: ret[key] = value for _, (key, value) in address_merged.items(): ret[key] = value ret['Content-Type'] = 'multipart/mixed' # Attach the body to the EmailMessage instance. msgMain = MIMEMultipart('related') ret.attach(msgMain) bodyParts = MIMEMultipart('alternative') msgMain.attach(bodyParts) c = Charset('utf-8') c.body_encoding = QP if self.body: bodyParts.attach(MIMEText(self.body, 'plain', c)) if self.htmlBody: bodyParts.attach(MIMEText(self.htmlBody.decode('utf-8'), 'html', c)) # Process attachments. for att in self.attachments: if att.dataType: if hasattr(att.dataType, 'asEmailMessage'): # Replace the extension with '.eml'. filename = att.name or '' if filename.lower().endswith('.msg'): filename = filename[:-4] + '.eml' msgMain.attach(att.data.asEmailMessage()) else: if issubclass(att.dataType, bytes): data = att.data elif issubclass(att.dataType, MSGFile): if hasattr(att.dataType, 'asBytes'): data = att.asBytes else: data = att.data.exportBytes() else: raise ConversionError(f'Could not find a suitable method to attach attachment data type "{att.dataType}".') mime = att.mimetype or 'application/octet-stream' mainType, subType = mime.split('/')[0], mime.split('/')[-1] # Need to do this manually instead of using add_attachment. attachment = EmailMessage() attachment.set_content(data, maintype = mainType, subtype = subType, cid = att.contentId) # This is just a very basic check. attachment['Content-Disposition'] = f'{"inline" if att.hidden else "attachment"}; filename="{att.getFilename()}"' # Add the attachment. msgMain.attach(attachment) return ret def deencapsulateBody(self, rtfBody: bytes, bodyType: DeencapType) -> Optional[Union[bytes, str]]: """ A method to deencapsulate the specified body from the RTF body. Returns a string for plain text and bytes for HTML. If specified, uses the deencapsulation override function. Returns ``None`` if nothing could be deencapsulated. If you want to change the deencapsulation behaviour in a base class, simply override this function. """ if rtfBody: bodyType = DeencapType(bodyType) if bodyType == DeencapType.PLAIN: if self.__deencap: try: return self.__deencap(rtfBody, DeencapType.PLAIN) except DeencapMalformedData: logger.exception('Custom deencapsulation function reported encapsulated data was malformed.') except DeencapNotEncapsulated: logger.exception('Custom deencapsulation function reported data is not encapsulated.') else: if self.deencapsulatedRtf and self.deencapsulatedRtf.content_type == 'text': return self.deencapsulatedRtf.text else: if self.__deencap: try: return self.__deencap(rtfBody, DeencapType.HTML) except DeencapMalformedData: logger.exception('Custom deencapsulation function reported encapsulated data was malformed.') except DeencapNotEncapsulated: logger.exception('Custom deencapsulation function reported data is not encapsulated.') else: if self.deencapsulatedRtf and self.deencapsulatedRtf.content_type == 'html': return self.deencapsulatedRtf.html if bodyType == DeencapType.PLAIN: logger.info('Could not deencapsulate plain text from RTF body.') else: logger.info('Could not deencapsulate HTML from RTF body.') else: logger.info('No RTF body to deencapsulate from.') return None def dump(self) -> None: """ Prints out a summary of the message. """ print('Message') print('Subject:', self.subject) if self.date: print('Date:', self.date.__format__(self.datetimeFormat)) print('Body:') print(self.body) def getInjectableHeader(self, prefix: str, joinStr: str, suffix: str, formatter: Callable[[str, str], str]) -> str: """ Using the specified prefix, suffix, formatter, and join string, generates the injectable header. Prefix is placed at the beginning, followed by a series of format strings joined together with the join string, with the suffix placed afterwards. Effectively makes this structure: {prefix}{formatter()}{joinStr}{formatter()}{joinStr}...{formatter()}{suffix} Formatter be a function that takes first a name variable then a value variable and formats the line. If self.headerFormatProperties is None, immediately returns an empty string. """ allProps = self.headerFormatProperties if allProps is None: return '' formattedProps = [] for entry in allProps: isGroup = False entryUsed = False # This is how we handle the groups. if isinstance(allProps[entry], dict): props = allProps[entry] isGroup = True else: props = {entry: allProps[entry]} for name in props: if props[name]: if isinstance(props[name], tuple): if props[name][1]: value = props[name][0] or '' elif props[name][0] is not None: value = props[name][0] else: continue else: value = props[name] entryUsed = True formattedProps.append(formatter(name, value)) # Now if we are working with a group, add an empty entry to get a # second join string between this section and the last, but *only* # if any of the entries were used. if isGroup and entryUsed: formattedProps.append('') # If the last entry is empty, remove it. We don't want extra spacing at # the end. if formattedProps[-1] == '': formattedProps.pop() return prefix + joinStr.join(formattedProps) + suffix def getJson(self) -> str: """ Returns the JSON representation of the Message. """ return json.dumps({ 'from': self.sender, 'to': self.to, 'cc': self.cc, 'bcc': self.bcc, 'subject': self.subject, 'date': self.date.__format__(self.datetimeFormat) if self.date else None, 'body': self.body, }) def getSaveBody(self, **_) -> bytes: """ Returns the plain text body that will be used in saving based on the arguments. :param _: Used to allow kwargs expansion in the save function. Arguments absorbed by this are simply ignored. """ # Get the type of line endings. crlf = inputToString(self.crlf, 'utf-8') prefix = '' suffix = crlf + '-----------------' + crlf + crlf joinStr = crlf formatter = (lambda name, value: f'{name}: {value}') header = self.getInjectableHeader(prefix, joinStr, suffix, formatter).encode('utf-8') return header + inputToBytes(self.body, 'utf-8') def getSaveHtmlBody(self, preparedHtml: bool = False, charset: str = 'utf-8', **_) -> bytes: """ Returns the HTML body that will be used in saving based on the arguments. :param preparedHtml: Whether or not the HTML should be prepared for standalone use (add tags, inject images, etc.). :param charset: If the html is being prepared, the charset to use for the Content-Type meta tag to insert. This exists to ensure that something parsing the html can properly determine the encoding (as not having this tag can cause errors in some programs). Set this to ``None`` or an empty string to not insert the tag. (Default: 'utf-8') :param _: Used to allow kwargs expansion in the save function. Arguments absorbed by this are simply ignored. """ if self.htmlBody: # Inject the header into the data. data = self.injectHtmlHeader(prepared = preparedHtml) # If we are preparing the HTML, then we should if preparedHtml and charset: bs = bs4.BeautifulSoup(data, features = 'html.parser', from_encoding = self._htmlEncoding) self._getHtmlEncoding(bs) if not bs.find('meta', {'http-equiv': 'Content-Type'}): # Setup the attributes for the tag. tagAttrs = { 'http-equiv': 'Content-Type', 'content': f'text/html; charset={charset}', } # Create the tag. tag = bs4.Tag(parser = bs, name = 'meta', attrs = tagAttrs, can_be_empty_element = True) # Add the tag to the head section. if bs.find('head'): bs.find('head').insert(0, tag) else: # If we are here, the head doesn't exist, so let's add # it. if bs.find('html'): # This should always be true, but I want to be safe. head = bs4.Tag(parser = bs, name = 'head') head.insert(0, tag) bs.find('html').insert(0, head) data = bs.encode('utf-8') return data else: return self.htmlBody or b'' def getSavePdfBody(self, wkPath = None, wkOptions = None, **kwargs) -> bytes: """ Returns the PDF body that will be used in saving based on the arguments. :param wkPath: Used to manually specify the path of the wkhtmltopdf executable. If not specified, the function will try to find it. Useful if wkhtmltopdf is not on the path. If :param pdf: is ``False``, this argument is ignored. :param wkOptions: Used to specify additional options to wkhtmltopdf. this must be a list or list-like object composed of strings and bytes. :param kwargs: Used to allow kwargs expansion in the save function. Arguments absorbed by this are simply ignored, except for keyword arguments used by :meth:`getSaveHtmlBody`. :raises ExecutableNotFound: The wkhtmltopdf executable could not be found. :raises WKError: Something went wrong in creating the PDF body. """ # Immediately try to find the executable. wkPath = findWk(wkPath) # First thing is first, we need to parse our wkOptions if they exist. if wkOptions: try: # Try to convert to a list, whatever it is, and fail if it is # not possible. parsedWkOptions = [*wkOptions] except TypeError: raise TypeError(f':param wkOptions: must be an iterable, not {type(wkOptions)}.') else: parsedWkOptions = [] # Confirm that all of our options we now have are either strings or # bytes. if not all(isinstance(option, (str, bytes)) for option in parsedWkOptions): raise TypeError(':param wkOptions: must be an iterable of strings and bytes.') processArgs = [wkPath, *parsedWkOptions, '-', '-'] # Log the arguments. logger.info(f'Converting to PDF with the following arguments: {processArgs}') # Get the html body *before* calling Popen. htmlBody = self.getSaveHtmlBody(**kwargs) # We call the program to convert the html, but give tell it the data # will go in and come out through stdin and stdout, respectively. This # way we don't have to write temporary files to the disk. We also ask # that it be quiet about it. process = subprocess.run(processArgs, input = htmlBody, stdout = subprocess.PIPE, stderr = subprocess.PIPE) # Give the program the data and wait for the program to finish. #output = process.communicate(htmlBody) # If it errored, throw it as an exception. if process.returncode != 0: raise WKError(process.stderr.decode('utf-8')) return process.stdout def getSaveRtfBody(self, **_) -> bytes: """ Returns the RTF body that will be used in saving based on the arguments. :param kwargs: Used to allow kwargs expansion in the save function. Arguments absorbed by this are simply ignored. """ # Inject the header into the data. return self.injectRtfHeader() def injectHtmlHeader(self, prepared: bool = False) -> bytes: """ Returns the HTML body from the MSG file (will check that it has one) with the HTML header injected into it. :param prepared: Determines whether to be using the standard HTML (``False``) or the prepared HTML (``True``) body. (Default: ``False``) :raises AttributeError: The correct HTML body cannot be acquired. """ if not self.htmlBody: raise AttributeError('Cannot inject the HTML header without an HTML body attribute.') body = None # We don't do this all at once because the prepared body is not cached. if prepared: body = self.htmlBodyPrepared # If the body is not valid or not found, raise an AttributeError. if not body: raise AttributeError('Cannot find a prepared HTML body to inject into.') else: body = self.htmlBody # Validate the HTML. if not validateHtml(body, self._htmlEncoding): logger.warning('HTML body failed to validate. Code will attempt to correct it.') # If we are here, then we need to do what we can to fix the HTML # body. Unfortunately this gets complicated because of the various # ways the body could be wrong. If only the tag is missing, # then we just need to insert it at the end and be done. If both # the and tag are missing, we determine where to put # the body tag (around everything if there is no tag, # otherwise at the end) and then wrap it all in the tag. parser = bs4.BeautifulSoup(body, features = 'html.parser', from_encoding = self._htmlEncoding) self._getHtmlEncoding(parser) if not parser.find('html') and not parser.find('body'): if parser.find('head') or parser.find('footer'): # Create the parser we will be using for the corrections. correctedHtml = bs4.BeautifulSoup(b'', features = 'html.parser') htmlTag = correctedHtml.find('html') # Iterate over each of the direct descendents of the parser and # add each to a new tag if they are not the head or footer. bodyTag = parser.new_tag('body') # What we are going to be doing will be causing some of the tags # to be moved out of the parser, and so the iterator will end up # pointing to the wrong place after that. To compensate we first # create a tuple and iterate over that. for tag in tuple(parser.children): if tag.name.lower() in ('head', 'footer'): correctedHtml.append(tag) else: bodyTag.append(tag) # All the tags should now be properly in the body, so let's # insert it. if correctedHtml.find('head'): correctedHtml.find('head').insert_after(bodyTag) elif correctedHtml.find('footer'): correctedHtml.find('footer').insert_before(bodyTag) else: # Neither a head or a body are present, so just append it to # the main tag. htmlTag.append(bodyTag) else: # If there is no , ,