Flask IMAP 应用程序检索不必要和不正确的字符

Flask IMAP application retrieving unnecessary and incorrect characters

应用程序使用 get_payload() 方法检索消息的 HTML。问题在于检索到的 HTML 由 \r\t\n 的随机序列组成。基本上,HTML 在 Gmail 和我的应用程序之间不匹配。

我仔细查看了 Gmail 和我的应用程序中的 html。 Gmail 有一个 <td height="32"></td> 标签,里面什么也没有,而我的应用程序只有一串无用的字符,如下图所示。电子邮件中没有这些字符,只有空白 space 或什么都没有。知道我为什么会收到这个吗?

注意:这种情况发生在其他电子邮件中,即使是纯文本电子邮件也是如此。

以下是我在Python

中使用的代码
import email
import email.header
import datetime
import imaplib
import sys
from pprint import pprint

imap_host = 'imap.gmail.com'
imap_user = 'someEmail@gmail.com'
imap_pass = 'somePassword'

diction = []


def process_mailbox(m):

    rv, data = m.search(None, "ALL")
    if rv != 'OK':
        print('No messages found!')
        return

    for num in data[0].split():
        rv, data = m.fetch(num, '(RFC822)')
        if rv != 'OK':
            print("ERROR getting message", num)
            return

        msg = email.message_from_bytes(data[0][1])
        hdr = email.header.make_header(email.header.decode_header(msg['Subject']))
        subject = str(hdr)
        print('Message %s: %s' % (num, subject))

        # date_tuple = email.utils.parsedate_tz(msg['Date'])
        # if date_tuple:
        #   local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))
        #   print('Local Date:', local_date.strftime('%a, %d %b %Y %H:%m:%S'))
        for part in msg.walk():
            if part.get_content_type() == 'text/html':
                # print(part.get_payload(decode=True))
                diction.append({'body': part.get_payload(decode=True)})
    return diction


M = imaplib.IMAP4_SSL('imap.gmail.com')

try:
    rv, data = M.login(imap_user, imap_pass)
except imaplib.IMAP4.error:
    print("LOGIN FAILED!")
    sys.exit(1)

# print(rv, data)

rv, mailboxes = M.list()
if rv == 'OK':
    print('Mailboxes:')
    print(mailboxes)

rv, data = M.select('Inbox')
if rv == 'OK':
    print('Processing mailbox...\n')
    process_mailbox(M)
    M.close()
else:
    print('ERROR: Unable to open mailbox', rv)
    M.logout()

这是烧瓶代码:

from flask import Flask, render_template, url_for
from forms import RegistrationForm, LoginForm

import email_client


a = email_client.diction

app = Flask(__name__)


@app.route('/test')
def test():
    return render_template('test.html', text=a)


@app.route('/')
@app.route('/email')
def home():
    return render_template('home.html')


@app.route('/about')
def about():
    return render_template('about.html', title='About')


@app.route('/register')
def register():
    form = RegistrationForm()
    return render_template('register.html', title='Register', form=form)


if __name__ == '__main__':
    app.run(debug=True)

和 HTML:

{% for t  in text %}
<div class="card content-section">
    <div class="card-body">
        {{ t.body |safe}}
    </div>
</div>
{% endfor %}

编辑:

我添加了 Markup 导入,并将读取邮件正文的 for 循环更改为:

        for part in msg.walk():
        if part.get_content_type() == 'text/html':
            value = Markup(part.get_payload(decode=True))
            print(value)
            diction.append({'body': value})

我找到了解决方案

part.get_payload(decode=True).decode('utf-8')

会解决问题