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

标签 python html flask imap

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

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

注意:这种情况发生在其他电子邮件中,即使只是一封纯文本的电子邮件。

enter image description here

以下是我在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()

这是 flask 代码:

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 %}

编辑:

我添加了标记导入,并将读取消息正文的 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})

最佳答案

我找到了解决方案Actual Result

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

解决问题

关于python - Flask IMAP 应用程序检索不必要和不正确的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53983097/

相关文章:

python - 指定分类特征列的形状?

php - 设置默认选中的 php 单选按钮

python - 如何将 url 参数作为字符串元组传递给 mysql 查询

python - 按设定长度的行打印列表(Python)

python - 使用轮廓裁剪手机屏幕

python - 优化: Dumping JSON from a Streaming API to Mongo

python - 301 使用 Flask 将旧 URL 重定向到新 URL

javascript - 如何像php页面中的新闻提要一样在循环中垂直滚动div内容

php - 在搜索栏中,当我搜索关键字时,无论表中是否有匹配项,它仍然没有页面

python - 使用 Juggernaut 向客户端发送实时数据