Python IMAP for Human beings

Imbox - Python IMAP for Humans

Build Status

Python library for reading IMAP mailboxes and converting email content to machine readable data

Requirements

Python (3.3, 3.4, 3.5, 3.6, 3.7)

Installation

pip install imbox

Usage

from imbox import Imbox

# SSL Context docs https://docs.python.org/3/library/ssl.html#ssl.create_default_context

with Imbox('imap.gmail.com',
        username='username',
        password='password',
        ssl=True,
        ssl_context=None,
        starttls=False) as imbox:

    # Get all folders
    status, folders_with_additional_info = imbox.folders()

    # Gets all messages from the inbox
    all_inbox_messages = imbox.messages()

    # Unread messages
    unread_inbox_messages = imbox.messages(unread=True)

    # Flagged messages
    inbox_flagged_messages = imbox.messages(flagged=True)

    # Un-flagged messages
    inbox_unflagged_messages = imbox.messages(unflagged=True)

    # Flagged messages
    flagged_messages = imbox.messages(flagged=True)

    # Un-flagged messages
    unflagged_messages = imbox.messages(unflagged=True)

    # Messages sent FROM
    inbox_messages_from = imbox.messages(sent_from='[email protected]')

    # Messages sent TO
    inbox_messages_to = imbox.messages(sent_to='[email protected]')

    # Messages received before specific date
    inbox_messages_received_before = imbox.messages(date__lt=datetime.date(2018, 7, 31))

    # Messages received after specific date
    inbox_messages_received_after = imbox.messages(date__gt=datetime.date(2018, 7, 30))

    # Messages received on a specific date
    inbox_messages_received_on_date = imbox.messages(date__on=datetime.date(2018, 7, 30))

    # Messages whose subjects contain a string
    inbox_messages_subject_christmas = imbox.messages(subject='Christmas')

    # Messages whose UID is greater than 1050
    inbox_messages_uids_greater_than_1050 = imbox.messages(uid__range='1050:*')

    # Messages from a specific folder
    messages_in_folder_social = imbox.messages(folder='Social')

    # Some of Gmail's IMAP Extensions are supported (label and raw):
    all_messages_with_an_attachment_from_martin = imbox.messages(folder='all', raw='from:[email protected] has:attachment')
    all_messages_labeled_finance = imbox.messages(folder='all', label='finance')

    for uid, message in all_inbox_messages:
    # Every message is an object with the following keys

        message.sent_from
        message.sent_to
        message.subject
        message.headers
        message.message_id
        message.date
        message.body.plain
        message.body.html
        message.attachments

    # To check all available keys
        print(message.keys())


    # To check the whole object, just write

        print(message)

        {
        'headers':
            [{
                'Name': 'Received-SPF',
                'Value': 'pass (google.com: domain of ......;'
            },
            {
                'Name': 'MIME-Version',
                'Value': '1.0'
            }],
        'body': {
            'plain': ['ASCII'],
            'html': ['HTML BODY']
        },
        'attachments':  [{
            'content': <StringIO.StringIO instance at 0x7f8e8445fa70>,
            'filename': "avatar.png",
            'content-type': 'image/png',
            'size': 80264
        }],
        'date': u 'Fri, 26 Jul 2013 10:56:26 +0300',
        'message_id': u '51F22BAA.1040606',
        'sent_from': [{
            'name': u 'Martin Rusev',
            'email': '[email protected]'
        }],
        'sent_to': [{
            'name': u 'John Doe',
            'email': '[email protected]'
        }],
        'subject': u 'Hello John, How are you today'
        }

    # With the message id, several actions on the message are available:
    # delete the message
    imbox.delete(uid)

    # mark the message as read
    imbox.mark_seen(uid)

Changelog

Changelog

Running the tests

You can run the imbox tests with tox.

Requirements:
  • the supported python versions
  • tox. Tox is packaged in Debian and derivatives distributions.

On Ubuntu, you can install several python versions with:

sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.X
Owner
Martin Rusev
Software / Privacy / Vegan
Martin Rusev
Comments
  • got an unexpected keyword argument 'ssl_context'

    got an unexpected keyword argument 'ssl_context'

    Please note that: ssl_context = pythonssllib.create_default_context() is new in python version 2.7.9.

    after installing 2.7.11, i get this error:

    >>> imbox = Imbox('imap.gmail.com', username='[email protected]', password='...')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/home/naruto/Programming/imap_test/venv/lib/python2.7/site-packages/imbox/__init__.py", line 15, in __init__
        ssl_context=None)
      File "/home/naruto/Programming/imap_test/venv/lib/python2.7/site-packages/imbox/imap.py", line 28, in __init__
        self.server = self.transport(self.hostname, self.port, **kwargs)
    TypeError: __init__() got an unexpected keyword argument 'ssl_context'
    

    looks like ssl_context argument is not supported in 2.7

  • parse_attachment function line 129 indented less?

    parse_attachment function line 129 indented less?

    https://github.com/martinrusev/imbox/blob/085da0738ec7adc87cc3ee9b4a827ba71a9c9182/imbox/parser.py#L108-L130

    attachment ['filename '] is assigned on lines 110 and 129, but line 129 will override the previous value anyway, Is this a bug?

  • error when parsing attachment

    error when parsing attachment

    I am running the example provided by README, My python version is 3.5, on windows platform, here is the error message, please take a look.

    Traceback (most recent call last):
      File "C:\Users\**\Miniconda3\lib\base64.py", line 518, in _input_type_check
        m = memoryview(s)
    TypeError: memoryview: a bytes-like object is required, not 'str'
    The above exception was the direct cause of the following exception:
    Traceback (most recent call last):
      File "D:/Project/account-adapter/imbox_downloader.py", line 61, in <module>
        for uid, message in all_messages:
      File "C:\Users\**\Miniconda3\lib\site-packages\imbox\__init__.py", line 50, in fetch_list
        yield (uid, self.fetch_by_uid(uid))
      File "C:\Users\**\Miniconda3\lib\site-packages\imbox\__init__.py", line 41, in fetch_by_uid
        email_object = parse_email(raw_email)
      File "C:\Users\**\Miniconda3\lib\site-packages\imbox\parser.py", line 160, in parse_email
        attachment = parse_attachment(part)
      File "C:\Users\**\Miniconda3\lib\site-packages\imbox\parser.py", line 102, in parse_attachment
        name, value = decode_param(param)
      File "C:\Users\**\Miniconda3\lib\site-packages\imbox\parser.py", line 74, in decode_param
        value = base64.decodestring(code)
      File "C:\Users\**\Miniconda3\lib\base64.py", line 560, in decodestring
        return decodebytes(s)
      File "C:\Users\**\Miniconda3\lib\base64.py", line 552, in decodebytes
        _input_type_check(s)
      File "C:\Users\**\Miniconda3\lib\base64.py", line 521, in _input_type_check
        raise TypeError(msg) from err
    TypeError: expected bytes-like object, not str
    
    
  • How does one tell if an email is read/unread?

    How does one tell if an email is read/unread?

    I see the function to mark items as read... but how do you tell if a message is read or unread already? For example, say I'm going to list all the emails in the inbox, and I need to somehow flag read items with a different background color or something... A pretty basic requirement. However, I don't see this information in the output from messages() or any other fetch_* method. Am I missing something?

  • Body.html strange characters

    Body.html strange characters "\r\n"

    ghhhh

    I'm displaying the result of body['html'] in an html page. What can I do to delete all those "new line" characters from the body of the mail? is it a bug?

    I'm currently fetching mails from an outlook account.

  • fix substring search of subjects in Gmail, add support for some Gmail extended IMAP

    fix substring search of subjects in Gmail, add support for some Gmail extended IMAP

    moved build_search_query to Messages, refactored to use a class attribute of IMAP_ATTRIBUTE_LOOKUP, so that the vendors package can overwrite and add entries to it for, for example, Gmail's IMAP extensions. added X-GM-RAW to GmailMessages' copy of the lookup to make partial subject searches work.

  • create vendors module to support idiosyncratic IMAP providers

    create vendors module to support idiosyncratic IMAP providers

    This was alluded to in #123. Here are a few things such a module could support:

    • map flag names to standardized folder names, and vice versa. For example, in Gmail the archived messages correspond with "[Gmail]/All Mail" (including the double quotes!), whereas in Yahoo Mail it's Archive
    • when there's an authentication error when instantiating Imbox, helpful error messages might be displayed. For example, with Yahoo: Have you clicked "Allow apps that use less secure sign in" here?: https://login.yahoo.com/account/security.
    • support IMAP extensions, which at least Gmail uses. (also alluded to in #123)

    Would you accept a PR that accomplishes this, at least for a few large IMAP providers?

  • TypeError: __init__() got an unexpected keyword argument 'starttls' (Imbox class)

    TypeError: __init__() got an unexpected keyword argument 'starttls' (Imbox class)

    Version: 0.9. Imbox class __init__ method help text:

    __init__(self, hostname, username=None, password=None, ssl=True, port=None, ssl_context=None, policy=None)

  • UTF-8/UnicecodeDecodeError

    UTF-8/UnicecodeDecodeError

    Name: imbox Version: 0.8.5

    Seeing decoding exceptions on certain messages

    'utf-8' codec can't decode byte 0xa9 in position 21957: invalid start byte" type="<class 'UnicodeDecodeError'> File "/usr/lib64/python3.4/site-packages/imbox/init.py", line 50, in fetch_list yield (uid, self.fetch_by_uid(uid)) File "/usr/lib64/python3.4/site-packages/imbox/init.py", line 41, in fetch_by_uid email_object = parse_email(raw_email) File "/usr/lib64/python3.4/site-packages/imbox/parser.py", line 126, in parse_email raw_email = str_encode(raw_email, 'utf-8') File "/usr/lib64/python3.4/site-packages/imbox/utils.py", line 10, in str_encode return str(value, encoding, errors)""

  • Python Error (most likely due to a circular import)

    Python Error (most likely due to a circular import)

    I wanted to check the python imap code on your github page and i got:

    PS D:\APPS_DEV_Dev_Sources\WINDOWS\Python> py imbox.py Traceback (most recent call last): File "D:\APPS_DEV_Dev_Sources\WINDOWS\Python\imbox.py", line 1, in from imbox import Imbox File "D:\APPS_DEV_Dev_Sources\WINDOWS\Python\imbox.py", line 1, in from imbox import Imbox ImportError: cannot import name 'Imbox' from partially initialized module 'imbox' (most likely due to a circular import) (D:\APPS_DEV_Dev_Sources\WINDOWS\Python\imbox.py) PS D:\APPS_DEV_Dev_Sources\WINDOWS\Python> pip --version pip 21.3.1 from C:\Users\bosley\AppData\Local\Programs\Python\Python39\lib\site-packages\pip (python 3.9) PS D:\APPS_DEV_Dev_Sources\WINDOWS\Python> pip show imbox Name: imbox Version: 0.9.8 Summary: Python IMAP for Human beings Home-page: https://github.com/martinrusev/imbox Author: Martin Rusev Author-email: [email protected] License: MIT Location: c:\users\bosley\appdata\local\programs\python\python39\lib\site-packages Requires: chardet Required-by: PS D:\APPS_DEV_Dev_Sources\WINDOWS\Python>

  • fix multipart filename disposition

    fix multipart filename disposition

    When attach filename is too long the function parse_attachment returns only last part name of the file.

    As example:

    Content-Disposition: attachment; filename0="2019-09-22-is_a_vee-.ryyyyyyyyyyy_looooong_name_______file.cs"; filename1="v.zip"

    so function parse_attachment returns as filename "v.zip".

  • when a new release on pypi? (>0.9.6)

    when a new release on pypi? (>0.9.6)

    Hi, are you planning for a new release to pypi soon? This project is quite handy and I'm using it in a couple of projects of my own, but since the latest release (0.9.6) in 2018 many bugs have been fixed. It would be nice to be able to get it from pypi.

    Thanks Regards

  • Content-type

    Content-type "application/ms-tnef" support.

    Is there a plan to support parse content-type "application/ms-tnef" attachments?

    When a email has content-type "application/ms-tnef" attachments, filename "winmail.dat", the "winmail.dat" need to be parsed to get the true attachments.

  • invalid literal for int() with base 10: '' for clause

    invalid literal for int() with base 10: '' for clause

    When my code runs "for uid, message in all_inbox_messages:", shows invalid literal for int() with base 10: '' for clause Follows the log.

    Exception in thread Thread-535: Traceback (most recent call last): File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/local/lib/python3.8/site-packages/flaskthreads/thread_helpers.py", line 191, in run super().run() File "/usr/local/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/usr/src/app/app/views/omnimail/controllers/ListEmails.py", line 33, in run Email.list(config)
    File "/usr/src/app/app/entities/Email.py", line 68, in list for uid, message in all_inbox_messages: File "/usr/local/lib/python3.8/site-packages/imbox/messages.py", line 55, in _fetch_email_list yield uid, self._fetch_email(uid) File "/usr/local/lib/python3.8/site-packages/imbox/messages.py", line 42, in _fetch_email return fetch_email_by_uid(uid=uid, File "/usr/local/lib/python3.8/site-packages/imbox/parser.py", line 155, in fetch_email_by_uid email_object = parse_email(raw_email, policy=parser_policy) File "/usr/local/lib/python3.8/site-packages/imbox/parser.py", line 212, in parse_email attachment = parse_attachment(part) File "/usr/local/lib/python3.8/site-packages/imbox/parser.py", line 122, in parse_attachment filename_parts.insert(int(s_name[1]),value[1:-1] if value.startswith('"') else value) ValueError: invalid literal for int() with base 10: ''

  • imap4.error

    imap4.error

    when I use letter instead of numbers it will ok. but when I use number email got a problem report below: case = imbox.messages(sent_from='[email protected]')

    UID command error: BAD [b'Could not parse command'] File "D:\python\test\test1.py", line 9, in case = imbox.messages(sent_from='[email protected]')

    sent_from='[email protected]' got report an issue, sent_from='[email protected]' this is fine, ok

  • decode_param issue

    decode_param issue

    I saved a bunch of files with this, one of which had a content disposition with a "" value containing a semicolon. The code broke because it tried to interpret the text after the colon as another param, but it isn't, didn't have an '=' in it, and that broke decode_param (unable to unpack split()).

    I fixed it for me by changing decode param with:

    if not "=" in param:
        return param, ""
    

    and that gave me enough info to work out the actual bug (as above).

    I would suggest keeping the check in decode_param, but the proper fix is of course to use a better disposition list splitter, that takes note of double quotes and treats the contents as one unit.

Related tags
:incoming_envelope: IMAP/SMTP sync system with modern APIs

Nylas Sync Engine The Nylas Sync Engine provides a RESTful API on top of a powerful email sync platform, making it easy to build apps on top of email.

Nov 16, 2022
Read/sync your IMAP mailboxes (python2)

Upstream status (master branch): Upstream status (next branch): Financial contributors: Links: Official github code repository: offlineimap Website: w

Nov 29, 2022
Python Email Sender (PES) is a program made with Python using smtplib, socket and tkinter.

Python Email Sender (PES) is a program made with Python using smtplib, socket and tkinter. This program was made for sender email to be a gmail account because that's what I used when testing it out, to make it work for a gmail account turn off secure app and then put in your email and password into the right variables and the program should be good to run!

Aug 26, 2022
A Python Mail Server

Salmon - A Python Mail Server Download: https://pypi.org/project/salmon-mail/ Source: https://github.com/moggers87/salmon Docs: https://salmon-mail.re

Nov 20, 2022
Send email in Python conveniently for gmail using yagmail
Send email in Python conveniently for gmail using yagmail

yagmail -- Yet Another GMAIL/SMTP client For the asynchronous asyncio version, look here: https://github.com/kootenpv/aioyagmail The goal here is to m

Dec 4, 2022
Python email address and Mime parsing library

Flanker - email address and MIME parsing for Python Flanker is an open source parsing library written in Python by the Mailgun Team. Flanker currently

Nov 29, 2022
A light-weight, modular, message representation and mail delivery framework for Python.

Marrow Mailer A highly efficient and modular mail delivery framework for Python 2.6+ and 3.2+, formerly called TurboMail. © 2006-2019, Alice Bevan-McG

Nov 12, 2022
A Discord Mod Mail bot made in python
A Discord Mod Mail bot made in python

Fish-Mail The mod mail bot for Fish Hosting Note: You are not allowed to remove the names in the credit command Note: If you want any ideas/commands a

Aug 30, 2022
Python library for sending emails.

Mail.py Python library for sending emails. Installation git clone https://github.com/SunPodder/Mail.py cd Mail.py python setup.py install Usage Imp

Oct 15, 2021
This simple python script uses cv2 to create and mail certificates to participants of workshops.
This simple python script uses cv2 to create and mail certificates to participants of workshops.

This simple python script uses cv2 to create and mail certificates to participants of workshops. Just collect the names and email ids of participants in a csv file (i used google docs), and place it in the project folder as given and run the script! Make sure to have 'Allow less secured apps' enabled for your gmail for smtp auth!

Oct 26, 2021
A python script that helps you understand why your E-Mail ended up in Spam
A python script that helps you understand why your E-Mail ended up in Spam

decode-spam-headers.py Whether you are trying to understand why a specific e-mail ended up in SPAM/Junk for your daily Administrative duties or for yo

Nov 23, 2022
A python program capable of accessing passwords associated with emails through leaked databases.
A python program capable of accessing passwords associated with emails through leaked databases.

passfind A python program capable of accessing passwords associated with emails through leaked databases. A python program capable of accessing passwo

Aug 14, 2022
Disposable Temporary Email (Python Library)

Disposable Temporary Email (Python Library)

Nov 24, 2022
Yahoo Mail Validator For Python

Validator Validator helps to know if the mail is valid or not Installation Install The libraries pip install requests bs4 colorama Usage Create a new

Mar 12, 2022
This python script will generate passwords for your emails, With certain lengths, And saves them into plain text files.

How to use. Change the Default length of genereated password in default.length.txt Type the email for your account. Type the website that the email an

Dec 26, 2021
Search email inbox with python and filter with search criteria via IMAP4 and fastapi or console

Search email inbox with python and filter with search criteria via IMAP4 and fastapi or console

Sep 7, 2021
A python mailserver meant for friends who value privacy and a hard to use interface....

python-mail A python mailserver meant for friends who value privacy and a hard to use interface.... Basic info This mailserver was just a random proje

Jan 19, 2022
Send Multiple Mail From List With Python

Send Multiple Mail From List With Python You can send multiple e-mail using HTML themes with Python. Here is the e-mail information to be sent. #The m

Dec 23, 2021
Disposable email validator for python

disposable-email-validator installation pip install disposable-email-validator

Jan 5, 2022