python html body,Python IMAPLIB HTML body parsing

问题

so basically i have this script that runs continuously and when a new email arrives in the inbox with specific text in the subject, it grabs information from the email. I have only managed to get it to pull the subject from the email but I cant get it do get the body of the email no matter what I try, I believe the email body is in HTML so i attempted to use BeautifulSoup to parse the body but that doesnt work at all. Please help!!! :( Here is what i have so far:

import email

import imaplib

from bs4 import BeautifulSoup

import time

import sys

username = 'xxx.xxx@xxx.xx'

password = 'xxxxxx'

mail = imaplib.IMAP4_SSL('imap-mail.outlook.com')

(retcode, capabilities) = mail.login(username, password)

mail.list()

n=0

while True:

mail.select('inbox')

(retcode, messages) = mail.search(None, 'UNSEEN', '(SUBJECT "xxxxxxx-

")', '(FROM "xx.xx@xxxx.xx")')

if retcode == 'OK':

for num in messages[0].split():

n=n+1

print('Processing Email ' + str(n))

typ, data = mail.fetch(num, '(RFC822)')

for response_part in data:

if isinstance(response_part, tuple):

original = email.message_from_bytes(response_part[1])

print("Subject: " + original['Subject'])

typ, data = mail.store(num,'+FLAGS','\\Seen')

time.sleep(120)

回答1:

Comment: The "body" returned by imap.fetch are usually bytes, not a string, which throws an exception

Change to:

msg = email.message_from_bytes(body)

Question: I cant get it do get the body of the email

For example:

import email, imaplib

username = 'xxx.xxx@xxx.xx'

password = 'xxxxxx'

imap = imaplib.IMAP4_SSL('imap-mail.outlook.com')

imap.login(username, password)

imap.select("inbox")

resp, items = imap.search(None, "(UNSEEN)")

for n, num in enumerate(items[0].split(), 1):

resp, data = imap.fetch(num, '(RFC822)')

body = data[0][1]

msg = email.message_from_string(body)

content = msg.get_payload(decode=True)

print("Message content[{}]:{}".format(n, content))

来源:https://stackoverflow.com/questions/52522113/python-imaplib-html-body-parsing

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值