Получить только тело письма, электронные письма из текстовых файлов

Я хочу удалить все отправленные теги from, to, cc, subject из этого текстового документа и сохранить только тело письма, чтобы я мог использовать его для обобщения содержимого документа. Как лучше всего это сделать в питоне. Я думаю, что лучше сначала сделать извлечение, а затем использовать предварительную обработку для этого случая. Также прикрепляю сюда код. Так что, если кто-нибудь может предложить, как это сделать, было бы очень полезно. Полезная нагрузка и часть файла ismultipart выполнены неправильно, и именно в этом я сомневаюсь, поэтому прокомментировал эту часть и потребовал помощи.

Прикрепите код и файл .txt ниже для справки.

import os, sys, csv
import glob
import re
import email
#from tika import parser
import warnings
warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
from gensim.summarization import summarize, keywords

# Set path to directory where files are
dirs = 'C:\\Users\\Lenovo\\.spyder-py3\\Testing\\'
#os.chdir(dirs)
for filename in glob.glob(os.path.join(dirs, '*.txt')):
    try:
        for files in filename:
            file = open(filename, 'r', encoding ='utf-8')
            filecontents = file.read()
            filecontents = re.sub(r'\s+', ' ', filecontents)
            print(filecontents)
            filecontents = filecontents.strip('\n')
            b = email.message_from_string(filecontents)# NEED
            if b.is_multipart():#HELP
                for payload in b.get_payload():#HERE
                    # if payload.is_multipart(): ...#SO
                    print (payload.get_payload())#COMMENTED
            else:#
                print (b.get_payload())#
            summary = summarize(filecontents, ratio =0.10)
            print(summary)
            kw = keywords(filecontents, words=15)
            print(kw)
            break
            #writer.writerow([file, summary, kw])
    except Exception as e:
        pass

ТЕКСТОВЫЙ ФАЙЛ

 Stephanie /ANN

From: Mr.A,  <[email protected]>
Sent: Wednesday, July 25, 2018 2:27 PM
To: , Tim /ANN; Abd, May /ANN
Cc: Mr.A, ; Theoder Jerry,
Subject: [EXTERNAL] RE:  Holdings: XXXX SPA – mfno.1322

Dear Dr. Tim A. , 

The option-2 is fine. By the way, we had received in the past Letter of Authorization for many companies other 
than Spa and I guess Xxxx does not do bANNiness with them either. If yes, then need to submit withdrawal 
of Letter of Authorization for those companies and send a Letter of Authorization for spa. stating for any 
applications submitted. We will send an administrative filing issue letter for both the holder and the agent.  



Thank you! 

Regards, 
 Mr.A 
PRODUCT Master File 
CDER 



Currently, there is no requirement to submit or resubmit NAs in any electronic format.  However, starting May 5, 2018, 
new NAs, as well as any submissions to the existing NAs mANNt be submitted electronically in legal (electronic Common 
Technical Document) format specified by GROUP A in the legal guidance. NA submissions that are not submitted in legal 
format after this date may be subject to rejection. For more information please check the NA website 
www.GROUP A.gov/abc/bca 


This communication is an informal communication consistent with which represents my best judgment 
at this time, but does not constitute an advisory opinion, does not necessarily represent the formal position of the 
GROUP A, and does not bind or otherwise obligate or commit the agency to the views expressed. This communication, 
including any attachments, is intended only for the person or entity to which it is addressed and may contain 
confidential material. Any review, retransmission, distribution or other ANNe of this information by persons or entities 
other than the intended recipient is prohibited. If you received this in error, please destroy any copies, contact the 
sender and delete the material from any computer. Thank you. 

From: [email protected] [mailto:[email protected]]  
Sent: Wednesday, July 25, 2018 2:10 PM 
To: Mr.A,  <[email protected]> 
Cc: [email protected] 
Subject: RE: Holdings: XXXX SPA ‐ dm 013383 

Dear , 


XXXX



2

Thanks for your phone call to clarify your needs and to understand the situation. I have confirmed that Xxxx only does 
direct bANNiness for test  S intermediate with b. and not with the other companies (e, 
x, etc.) that are secondary companies. Based on our discANNsion, I believe that we do not need to 
provide QAs for these secondary companies or mention them in our NA file as they would be covered under a 
separate QA  S.p.A. to them. If this is correct, then I believe you mentioned that we have two options as 
described below: 

Option 1: We can issue a separate QA for each . NA to be specific on which NA is being cross‐referenced 
to our NA 13383. 

Option 2: We can do a single QA for  and mention that they can cross‐reference any of their NAs. This 
would allow them to cross‐reference any of their 

If I have misunderstood or am incorrect in my response and we need to discANNs further, please let me know. 

If not, when you issue your request, can you please send to me and May Abd by email? 

Kind regards. 

Tim 

Tim A. , BsC 
Director, YY SERVICES) 
Xxxx ANN 
Phone/FAX: 2312333 
Cell: 23312123131 
Email: [email protected] 



From: , Tim /ANN  
Sent: Monday, July 23, 2018 7:05 AM 
To: 'Mr.A, ' 
Cc: Abd, May /ANN 
Subject: RE: [EXTERNAL] Holder: XXXX SPA - NA 013383 

Dear , 

May is now on vacation and I am covering for her during her absence. Is there a good time to call you today or later this 
week? Please let me know and we can schedule or please call my cell phone 21313131231 at your convenience. 

Kind regards. 

Tim 

Tim A. , MSC 
Director, PQR 
Xxxx 
Phone/FAX: 2312313313 
Cell: 3142342424 
Email: [email protected] 



XXXX



3


‐‐‐‐‐‐‐‐‐‐ Forwarded message ‐‐‐‐‐‐‐‐‐‐ 
From: "Mr.A, " <[email protected]> 
Date: Jul 20, 2018 9:01 AM 
Subject: [EXTERNAL] Holder: XXXX SPA ‐ NA 013383 
To: "TRETE/ANN" <[email protected]> 
Cc: "mno.com> 

Dear May Abd, 

. I need to talk to you on this.  

Thank you! 

Regards, 
 Mr.A 
PRODUCT Master File 
CDER 


Currently, there is no requirement to submit or resubmit NAs in any electronic format.   
format after this date may be subject to rejection. For more information please check the NA website 
www.GROUP A./cder/NA   


This communication is an informal communication  which represents my best judgment 
at this time, but does not constitute an advisory opinion, does not necessarily represent the formal position of the 
GROUP A, and does not bind or otherwise obligate or commit the agency to the views expressed. This communication, 
including any attachments, is intended only for the person or entity to which it is addressed and may contain 
confidential material. Any review, retransmission, distribution or other ANNe of this information by persons or entities 
other than the intended recipient is prohibited. If you received this in error, please destroy any copies, contact the 
sender and delete the material from any computer. Thank you. 


XXXX

person Swordsman    schedule 19.02.2019    source источник
comment
Только тело письма между тегами «Уважаемый» и «С уважением». Просто разговор   -  person Swordsman    schedule 19.02.2019
comment
Что делать, если в разговоре есть слово regards?   -  person DirtyBit    schedule 19.02.2019
comment
Это нормально и должно быть там. Только я хочу удалить содержимое тегов, а также теги в перенаправленном сообщении, от, в копию, отправлено, тема, телефон, ячейка, электронная почта из файла. На самом деле я хочу построить сводник, которому я буду передавать только тело файла.   -  person Swordsman    schedule 19.02.2019
comment
Вы понимаете, что заменили нас на ИНС во всем примере?   -  person tripleee    schedule 21.02.2019
comment
Что именно вы ожидаете от многокомпонентной обработки и обработки полезной нагрузки? Можем ли мы предположить, что все части тела содержат текст, который вы хотите обработать? Нет бинарных вложений? Нет составных/альтернативных? (Потому что тогда вы получите один и тот же текст дважды.)   -  person tripleee    schedule 21.02.2019


Ответы (1)


Не совсем понятно, с какой частью кода вам нужна помощь, что вы хотите, чтобы он делал вместо того, что он делает сейчас, или как правильно передать результаты для дальнейшей обработки.

Однако отмечу, что в вашем коде есть ряд проблем.

  • Вы не можете прочитать сообщение электронной почты как текст UTF-8. Независимо от расширения файла, сообщение RFC822 представляет собой просто последовательность байтов. Традиционная электронная почта может иметь большое количество различных кодировок, и если вы попытаетесь принудительно преобразовать ее в UTF-8, вы столкнетесь с UnicodeDecodeError и другими препятствиями.
  • Как всегда, одеяло except Exception: является серьезной ошибкой. Возможно, вы используете это только для отладки, но на самом деле это усложняет отладку.
  • Типичные современные сообщения электронной почты имеют довольно сложную структуру тела MIME, которую необходимо проанализировать в контексте, прежде чем решить, какие из них вы действительно хотите обработать. Одним из распространенных явлений является multipart/alternative, когда одно и то же сообщение отображается в разных форматах, чтобы получатели могли решить, хотят ли они прочитать его в виде HTML, обычного текста или, иногда, возможно, PDF или RTF, или отдельного изображения, или чего-то еще, в зависимости от заявление. Кроме того, HTML-структуры часто состоят из нескольких частей, потому что основной HTML-код хочет использовать небольшие изображения, которые также поставляются в структуре MIME (логотип компании, анимированные смайлики и другие оскорбления для читателя). Возможно, см. также Каковы части составного электронного письма?

Еще одна сложность для этого ответа заключается в том, что библиотека Python email относительно недавно подверглась капитальному ремонту. Новая функциональность была введена экспериментально в Python 3.3, но стала задокументированной версией по умолчанию только в версии 3.6. Большая часть кода, который вы обнаружите в дикой природе, будет использовать средства до версии 3.6, но в дальнейшем вы, вероятно, захотите ориентироваться на новый и улучшенный API.

С устаревшим API ваш код может выглядеть примерно так

from email import message_from_binary_file

for filename in glob.glob(os.path.join(dirs, '*.txt')):
    # Not useful; we already have a filename
    #for files in filename:
    # Open in binary mode, don't try to guess encoding
    # Use a context manager so we don't leave the file open
    with open(filename, 'rb') as file:
        # Just let the email library take it from here
        #filecontents = file.read()
        #filecontents = re.sub(r'\s+', ' ', filecontents)
        #print(filecontents)
        #filecontents = filecontents.strip('\n')
        b = email.message_from_binary_file(file)
    if b.is_multipart():
        # There are a number of things you could do to pick out
        # one or more payloads for analysis, but let's just take
        # the first text/plain part and call it "main_part"
        for part in b.walk()
            if part.get_content_type() == 'text/plain':
                main_part = part.get_payload()
                break
    else:
        main_part = b.get_payload()
    summary = summarize(main_part, ratio =0.10)
    print(summary)
    kw = keywords(main_part, words=15)
    print(kw)

Чтобы использовать новый API 3.6+, вам нужно будет адаптировать его к чему-то вроде

from email.policy import default as default_email_policy
...
    b = email.message_from_binary_file(file, policy=default_email_policy)
    main_part = b.get_body(['related', 'plain', 'html'])

Это приведет к созданию нового объекта email.message.EmailMessage, который будет иметь некоторые другие методы и поведение, отличные от устаревшего класса email.message.Message. Документация предполагает, что, возможно, однажды значение по умолчанию policy будет передано по умолчанию, и в этот момент старый код переключится на новое поведение (но также, вероятно, некоторое количество неприятных сюрпризов и явных поломок).

Обратите также внимание на метод get_body(), который является новым в версии 3.6 и позволяет легко выбрать «вероятную основную часть»; хотя, если часть text/plain недоступна, приведенный выше код вернется к HTML, который вам затем нужно будет обработать для извлечения фактического текста (см. Beautifulsoup может быть?)

Не существует технического, надежного и надежного способа отделить шаблоны (заголовки, подписи и т. д.) от фактического содержимого электронной почты. Некоторые почтовые HTML-клиенты могут давать подсказки в сгенерированном сообщении о том, какое <div> содержит то, что ввел пользователь, но в общем случае вам просто нужно пробираться по самые брови в (откровенно говоря, безнадежной) эвристике.

person tripleee    schedule 21.02.2019