E
E
expp2020-04-20 20:55:48
Python
expp, 2020-04-20 20:55:48

How to parse mail in python?

Good evening.

I receive certain letters in the mail, the title of which indicates a certain code, which means that it came on the topic that corresponds to this code. I need to parse these emails and get only emails with a specific code as output.

Please tell me how to do it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
del4pp, 2020-04-20
@del4pp

Python has the imaplib library, which allows you to receive letters from your mailbox via IMAP and parse them. Below is my code that I created for myself for the same task.

def read(sender_of_interest=None):
    imap = imaplib.IMAP4_SSL("imap.gmail.com", 993)
    imap.login('Почта', 'пароль')
    imap.select('INBOX')
    if sender_of_interest:
        status, response = imap.uid('search', None, 'UNSEEN', 'FROM {0}'.format(sender_of_interest))
    else:
        status, response = imap.uid('search', None, 'UNSEEN')
    if status == 'OK':
        unread_msg_nums = response[0].split()
    else:
        unread_msg_nums = []
    data_list = []
    for e_id in unread_msg_nums:
        e_id = e_id.decode('utf-8')
        _, response = imap.uid('fetch', e_id, '(RFC822)')
        html = response[0][1].decode('utf-8')
        email_message = email.message_from_string(html)
        data_list.append(email_message.get_payload())
    for elem in data_list:
        clean_html(elem)

and then everything is simple:
if "keyword" in array_with_messages[message index]:
...then what should be done if the keyword is found.
well, in a cycle of course

P
PoMaXapi, 2021-11-05
@PoMaXapi

mojno vot tsk:

import imaplib

email = '///...'
password = '///...'

mail = imaplib.IMAP4_SSL('imap.yandex.ru')
mail.login(email, password)
mail.list()
mail.select("inbox")

result, data = mail.search(None, "ALL")

ids = data[0]
id_list = ids.split()
latest_email_id = id_list[-1]

result, data = mail.fetch(latest_email_id, "(RFC822)")
raw_email = data[0][1]
raw_email_string = raw_email.decode('utf-8')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question