Useful email IMAP client written on Python for downloading emails and preparing them for further parsing. It also works with attachments and can be easily customised for particular needs.

Main encoding type is UTF-8 in this case, but if you will receive emails in quoted-printable or CP1251 from Windows Servers, just set needed encoding.

This version simply outputs: sender, subject and body sections into terminal output but can be modified to save all parts into separate files or database as records.

For example let's create a python file:

vim email-client.py

Then paste this code changing email credentials:

import os 
import email
import imaplib
import base64
from email.header import Header, decode_header, make_header
from email import message_from_bytes

#Email box credentials
EMAIL = 'receiver_box[at]email.com'
PASSWORD = 'password_goes_here'
SERVER = 'imap.server.com'
SAVE_PATH = '/path/for/files/to/be/saved'

mail = imaplib.IMAP4_SSL(SERVER)
mail.login(EMAIL, PASSWORD)
mail.select('inbox')
status, data = mail.search(None, '(UNSEEN)')
mail_ids = []
for block in data:
  mail_ids += block.split()
for i in mail_ids:
  status, data = mail.fetch(i, '(RFC822)')
  for response_part in data:
    if isinstance(response_part, tuple):
      message = email.message_from_bytes(response_part[1])
      mail_from = message['from']
      mail_from_decoded = mail_from.encode('utf-8', 'ignore')
      mail_subject = message['subject']
      mail_subject_decoded = make_header(decode_header(mail_subject))
      if message.is_multipart():
        content = ''
        for part in message.get_payload():
          if part.get_content_type() == 'text/plain':
            content += str(part.get_payload(decode=True), encoding="utf-8")
          elif part.get_content_type().startswith('application/'):
            filename = part.get_filename()
            if filename is not None:
              filename_decoded = make_header(decode_header(filename))
              filename_decoded_str = decode_header(filename_decoded)[0][0].decode('utf-8')
              file_path = os.path.join(SAVE_PATH, filename_decoded_str) 
              with open(file_path, 'wb') as f:
                f.write(part.get_payload(decode=True))
              print(f'Saved {filename_decoded} to: {SAVE_PATH}')
      else:
        content = str(message.get_payload(decode=True), encoding="utf-8")
      print(f'From: {mail_from_decoded}')
      print(f'Subject: {mail_subject_decoded}')
      print(f'Content: {content}')
      print(f'NEXT MESSAGE')
mail.close()
mail.logout()

Make file executable:

chmod +x email-client.py

Now let's try it working:

./email-client.py

No comments yet