将前缀div添加到电子邮件HTML正文

时间:2017-12-04 14:04:41

标签: python html gmail mime-types prefix


我们正在尝试向每个我们发现可疑的电子邮件添加警告,但是一旦我们这样做了 - 并非所有电子邮件在更改后都按预期显示: - 在某些电子邮件中,我们破坏了样式并且消息的显示方式不同,而在其他电子邮件上我们在电子邮件顶部看到警告(类似于Google警告)。

对于在电子邮件的HTML部分添加“前缀”警告的操作,是否有任何最佳做法?做什么/不做?什么都有帮助!

这是一个片段:

def replace_body(self, email_instance, message_id, **kwargs):
    def _generate_html_part_from_plain(_part):
        _plain_text_body = _part.get_payload(decode=True)
        _content_charset = _part.get_content_charset()
        _artificial_html_body = '<div dir="ltr">{}</div>'.format(_plain_text_body.replace('\r\n', '<br>'))
        _html_part = MIMEText(_artificial_html_body, 'html', _content_charset)
        return _content_charset, _html_part

    body_prefix = self.generate_prefix(message_id, email_instance, kwargs)

    if not body_prefix:
        log('prefix is empty, no need to update body (message={message_id})')
        return True

    if email_instance.is_multipart():
        payload = email_instance.get_payload()
        for part in payload:
            if part.get_content_subtype() == 'html':
                self.log.debug('email is \'multipart\' - attaching HTML part with warning (message={})'
                               .format(message_id))
                prefixed_part = self.attach_email_prefix(body_prefix, part, 'html', part.get_content_charset())
                payload.remove(part)
                payload.append(prefixed_part)
                break
        # when no html part present
        else:
            for part in payload:
                if part.get_content_subtype() == 'plain':
                    self.log.debug('email is \'multipart\', but no \'html\' part found: '
                                   'generating and attaching HTML part with warning (message={})'
                                   .format(message_id))
                    content_charset, html_part = _generate_html_part_from_plain(part)
                    prefixed_part = self.attach_email_prefix(body_prefix, html_part, 'html', content_charset)
                    top_content_subtype = email_instance.get_content_subtype()
                    if top_content_subtype != 'alternative':
                        self.log.debug('email\'s top-content-subtype is {}, generating alternative part to hold'
                                       '\'plain\' and \'html\' parts, and attaching to email (message={})'
                                       .format(top_content_subtype, message_id))
                        alternative_part = MIMEMultipart('alternative')
                        new_plain_part = MIMEText(part.get_payload(decode=True), 'plain', content_charset)
                        alternative_part.set_payload([new_plain_part, prefixed_part])
                        payload.remove(part)
                        payload.append(alternative_part)
                    else:
                        payload.append(prefixed_part)
                    break

        email_instance.set_payload(payload)
    elif email_instance.get_content_subtype() == 'plain':
        self.log.debug('email is \'text/plain\', attaching artificial HTML part with warning (message={})'
                       .format(message_id))
        # plain_part = deepcopy(email_instance)
        content_charset, html_part = _generate_html_part_from_plain(email_instance)
        prefixed_part = self.attach_email_prefix(body_prefix, html_part, 'html', content_charset)
        email_instance.replace_header('Content-Type', 'multipart/alternative')
        new_plain_part = MIMEText(email_instance.get_payload(decode=True), 'plain', content_charset)
        email_instance.set_payload([new_plain_part, prefixed_part])
        # email_instance.attach(html_part)
    else:
        self.log.warning('failed to attach HTML warning (message={}, top-content-type={})'
                         .format(message_id, email_instance.get_content_type()))

    log('prefix attached to message successfully (message={message_id})')
    return True

def attach_email_prefix(self, prefix, email_instance, subtype='html', charset='us-ascii'):
    def attach_to_text(_part):
        sep = {'html': '<br>', 'text': '\r\n'}
        _part_payload = _part.get_payload(decode=True)
        if not isinstance(_part_payload, str):
            self.log.debug(
                'skipping prefix attaching: Content payload\'s type is not str: {}'.format(_part_payload))
            return _part
        _part.set_payload('{}{}{}'.format(prefix, sep[subtype], _part_payload), charset)
        return _part

    if email_instance.get_content_subtype() == subtype:
        return attach_to_text(email_instance)

0 个答案:

没有答案