Я пытаюсь получить очищенное читаемое тело сообщения Gmail в python. Ниже мой код:
message = service.users().messages().get(userId= 'me', id=s_id).execute()
m_dict = { }
m_payld = message['payload']
mssg_parts = m_payld['parts']
part_one = mssg_parts[0]
part_body = part_one['body']
part_data = part_body['data']
clean_one = part_data.replace("-","+") # decoding from Base64 to UTF-8
clean_one = clean_one.replace("_","/")
clean_two = base64.b64decode(bytes(clean_one, 'UTF-8'))
soup = BeautifulSoup(clean_two , "lxml" )
mssg_body = soup.body()
m_dict['Message body'] = mssg_body
Как я могу изменить код, чтобы получить лучший результат?
Ниже мой измененный код:
def fetch_mail(mail_id):
mail_list = []
for ml_id in mail_id:
mail_dict = { }
m_id = ml_id['id'] # get id of individual message
message = service.users().messages().get(userId= 'me',
id=m_id).execute()
m_payld = message['payload'] # get payload of the message
m_head = m_payld['headers'] # getting message payload header
for sub in m_head: #Fetching the mail Subject
if sub['name'] == 'Subject':
m_subj = sub['value']
mail_dict['Subject'] = m_subj
else:
pass
for dt in m_head: # getting the date
if dt['name'] == 'Date':
mail_date = dt['value']
date_parse = (parser.parse(mail_date))
m_date = (date_parse.date())
mail_dict['Date'] = str(m_date)
else:
pass
for sender in m_head: # getting the Sender
if sender['name'] == 'From':
m_from = sender['value']
mail_dict['Sender'] = m_from
else:
pass
try:
# Fetching message body
mssg_parts = m_payld['parts'] # fetching the message parts
part_one = mssg_parts[0] # fetching first element of the part
part_body = part_one['body'] # fetching body of the message
part_data = part_body['data'] # fetching data from the body
clean_one = part_data.replace("-","+") # decoding from Base64 to UTF-8
clean_one = clean_one.replace("_","/") # decoding from Base64 to UTF-8
clean_two = base64.b64decode(bytes(clean_one, 'UTF-8')) # decoding from Base64 to UTF-8
soup = BeautifulSoup(clean_two , "lxml")
mssg_body = soup.body()
#print(mssg_body)
mail_dict['Message body'] = mssg_body
except:
pass
mail_list.append(mail_dict)
return mail_list
Я запустил сценарий следующим образом:
mail_details = fetch_mail(mail_id = mail_ids)
Теперь mail_details имеет только Тема, Дата и Отправитель. Ошибка не возвращается, и тело сообщения отсутствует в результате. Что делать?