python - Flask IMAP 应用程序检索不必要和不正确的字符
问题描述
应用程序使用 get_payload() 方法来检索消息的 HTML。问题是检索到的 HTML 由 和 的随机序列\r
组成\t
\n
。基本上,Gmail 和我的应用程序之间的 HTML 不匹配。
我仔细查看了 Gmail 和我的应用程序中的 html。Gmail 有一个<td height="32"></td>
标签,里面什么都没有,而我的应用程序只有一串无用的字符,如下图所示。而不是电子邮件中的那些字符,只有空格或什么都没有。知道为什么我会得到这个吗?
注意:这发生在其他电子邮件中,即使是纯文本电子邮件也是如此。
以下是我在 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 %}
编辑:
我添加了标记导入,并将读取消息正文的 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})
解决方案
推荐阅读
- java - 隐藏和显示后不显示浮动操作按钮图标图像
- java - Gson - 空 JsonElement 的 getAsBoolean
- asp.net - 如何在引导模式对话框中使用 MVC ValidationMessageFor
- android - 使列表视图中的项目默认选中
- python - Windows 上的 Python Behave BDD 教程错误
- python - 删除旧的 python 文件后在 windows 中运行 python 文件
- c# - PDF 表格在部分填写后不再可编辑
- sqlite - 使用jooq上下文将内存sqlite转储到字节[]
- python - Python“命令不同步”错误将批量插入MySQL
- performance - 关于实现高性能汇编指令生成器的建议