应用程序使用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 = 'phptest390@gmail.com'
imap_pass = 'Magickey20'
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})