简体   繁体   中英

Render html in Flask IMAP application

I am creating a Flask application which is supposed to retrieve emails by sending IMAP or POP requests to an email service provider like GMAIL. I am able to retrieve the emails by using the imaplib library. A simple email which contains only text in it is simple enough to retrieve and display. Unfortunately, when an email consists of images, GIFs or special styling it gets more difficult.

Whenever I run the code that retrieves the contents of the emails it seems that I am getting the HTML. But when I try to "render" it to an html file and use render_template('test.html') it seems I would be putting html into html.

What would be the correct way to move what I get from the email service provider to my web application in Flask?

class EmailClient:
imap_host = 'imap.gmail.com'
imap_user = 'test@test.com'
imap_pass = 'password'

def process_mailbox(M):
    diction = []

    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())
            diction.append(part.get_payload())

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() 

If you want to pass html code as a variable to a jinja template, add |safe. For instance if email contains the email in html format:

{{ email |safe }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM