Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Задача: http://forum.ru-board.com/topic.cgi?forum=8&bm=1&topic=82194
- # Почта: username@yandex.ru / password
- # TODO: после завершение - Убрать в настройках разрешение доступа по портальному паролю:
- # https://mail.yandex.ru/?uid=1130000012843751#setup/client
- # Использованы материалы: https://eax.me/python-imap/
- # Внешние зависимости:
- # pip install pandas
- # pip install tqdm
- # TODO: Добавить удаление дубликатов
- import imaplib
- import email
- from email.message import EmailMessage
- import pandas as pd
- from tqdm import tqdm
- print("\nStarted\n")
- imap = imaplib.IMAP4_SSL('imap.yandex.ru')
- imap.login('username@yandex.ru', 'password')
- # print(imap.list())
- imap.select("INBOX")
- result, mail_ids = imap.search(None, 'ALL')
- mail_ids = mail_ids[0].split()
- # print(mail_ids)
- contacts = pd.DataFrame(columns=['name', 'email', 'is_parsed'])
- for mail_ids in tqdm(mail_ids):
- status, data = imap.fetch(mail_ids, '(RFC822)')
- msg = email.message_from_bytes(data[0][1], _class=EmailMessage)
- # print(msg.items())
- is_parsed = False
- try:
- name, addr = email.utils.parseaddr(msg['From'])
- is_parsed = True
- except Exception as e:
- print(f"\nCannot parse msg['From']: '{msg['From']}'\n")
- name = msg['From']
- addr = ''
- if is_parsed:
- addr = addr.strip().lower()
- if name:
- name = name.strip()
- decoded_string, charset = email.header.decode_header(name)[0]
- if charset is not None:
- try:
- name = decoded_string.decode(charset)
- except UnicodeDecodeError:
- print(f"\nCannot decode name: '{name}'\n")
- name = ''
- else:
- name = decoded_string
- # print(f"\n{name}\t{addr}\t{is_parsed}")
- contacts = contacts.append({'name': name, 'email': addr, 'is_parsed': is_parsed}, ignore_index=True)
- with pd.ExcelWriter('pochta_serezhki_inbox.xlsx') as writer:
- contacts.to_excel(writer, sheet_name='contacts', startrow=0, startcol=0)
- print("\nCompleted\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement