Python IMAP for Human beings

Related tags

Emailimappython-imap
Overview

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
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

    opened by boussouira 10
  • 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?

    opened by walirt 5
  • 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
    
    
    opened by taoluo 5
  • 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?

    opened by agaskins 5
  • 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.

    opened by MattiaFailla 4
  • 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.

    opened by zevaverbach 4
  • 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?

    opened by zevaverbach 4
  • 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)

    opened by pawamoy 4
  • 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)""

    opened by nulfox 4
  • 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>

    opened by gilluc 3
  • 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".

    opened by mateodurante 3
  • Attachment parsing error

    Attachment parsing error

    I use another Python module [yagmail] to send an email with attachments. When I try to use the imbox module to read the email attachments sent by yagmail, the following error appears, which looks like an attachment name resolution error:

    File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/imbox/parser.py", line 212, in parse_ email attachment = parse_ attachment(part) File "/data/data/com.termux/files/usr/lib/python3.10/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: ''mmexport1670496727397.jpg

    opened by leonlinxs 0
  • 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

    opened by oberix 2
  • 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.

    opened by sangkaka 0
  • 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: ''

    opened by vncaragao 1
  • 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

    opened by jasonjiangxinhui 0
Releases(0.9.9)
  • 0.9.9(Nov 17, 2022)

    What's Changed

    • Add query uid__range by @skulltech in https://github.com/martinrusev/imbox/pull/153
    • fix substring search of subjects in Gmail, add support for some Gmail extended IMAP by @zevaverbach in https://github.com/martinrusev/imbox/pull/155
    • Support filter message by mail body by @daassh in https://github.com/martinrusev/imbox/pull/166
    • Attachments now getting Content-ID by @Anderseta in https://github.com/martinrusev/imbox/pull/174
    • Fix handling for attachments with file names longer than 76 characters by @tarx1234 in https://github.com/martinrusev/imbox/pull/186
    • attempt to fix issue 169/177 by @py-radicz in https://github.com/martinrusev/imbox/pull/184
    • Update parser.py in https://github.com/martinrusev/imbox/pull/192
    • Avoiding the error - ValueError: invalid literal for int() with base 10 by @Anderseta in https://github.com/martinrusev/imbox/pull/201
    • fix false exception on unknown encoding #202 by @kapalex in https://github.com/martinrusev/imbox/pull/203
    • Fix binascii.Error: Incorrect padding by @Anderseta in https://github.com/martinrusev/imbox/pull/204
    • Preserve timezone info in date parsing by @AT0myks in https://github.com/martinrusev/imbox/pull/205
    • Fix ignored headers + unnecessary major version check by @AT0myks in https://github.com/martinrusev/imbox/pull/206
    • Local variable 'filename' value is not used by @tveronesi in https://github.com/martinrusev/imbox/pull/211
    • Date handling improvement and various fixes by @AT0myks in https://github.com/martinrusev/imbox/pull/218
    • Fix crash when semicolon present in attachment name by @nicknytko in https://github.com/martinrusev/imbox/pull/219
    • Base64 decode param and recognize single file mails as attachment by @engelant in https://github.com/martinrusev/imbox/pull/224
    • [Fix] parse_attachment > cannot parse name by @jimmi2051 in https://github.com/martinrusev/imbox/pull/228
    • Should first get content charset then str_encode with charset. by @sangkaka in https://github.com/martinrusev/imbox/pull/231
    • fix append and join of param parts by @oberix in https://github.com/martinrusev/imbox/pull/232

    Full Changelog: https://github.com/martinrusev/imbox/compare/0.9.6...0.9.9

    Source code(tar.gz)
    Source code(zip)
  • 0.9.6(Aug 14, 2018)

    IMPROVEMENTS:

    • Vendors package, adding provider specific functionality (#139) - Contributed by @zevaverbach
    • Type hints for every method and function (#136) - Contributed by @zevaverbach
    • Move all code out of init.py and into a separate module (#130) - Contributed by @zevaverbach
    • Enhance `messages' generator: (#129) - Contributed by @zevaverbach
    Source code(tar.gz)
    Source code(zip)
  • 0.9.5(Dec 5, 2017)

    IMPROVEMENTS:

    • date__on support: (#109)
    • Starttls support: (#108)
    • Mark emails as flagged/starred: (#107)
    • Messages filter can use date objects instead of stringified dates: (#104)
    • Fix attachment parsing when a semicolon character ends the Content-Disposition line: (#100)
    • Parsing - UnicecodeDecodeError() fixes: (#96)
    • Imbox() with support: (#92)
    Source code(tar.gz)
    Source code(zip)
  • 0.9(Sep 18, 2017)

Owner
Martin Rusev
Software / Privacy / Vegan
Martin Rusev
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

Sun 4 Nov 24, 2021
PGP encrypted / multipart templated emails for Django

Created by Stephen McDonald Introduction django-email-extras is a Django reusable app providing the ability to send PGP encrypted and multipart emails

stephenmcd 75 May 14, 2022
Generate Email, Register for anything, Get the OTP/Link

OTE : One Time Email Introduction ote is a command line utility that generates temporary email address and automatically extracts OTPs or confirmation

Somdev Sangwan 457 Jan 03, 2023
Certificate generating and mailing system

skylab-certificate-system Through the this system, you can generate personalized certificates for people with name-surname-mail information in an exce

Oğuzhan Ercan 9 Sep 27, 2022
Fastapi mail system sending mails(individual, bulk) attachments(individual, bulk)

Fastapi-mail The fastapi-mail simple lightweight mail system, sending emails and attachments(individual && bulk) 🔨 Installation $ pip install fastap

Sabuhi 399 Dec 29, 2022
A Django email backend that uses a celery task for sending the email.

django-celery-email - A Celery-backed Django Email Backend A Django email backend that uses a Celery queue for out-of-band sending of the messages. Wa

Paul McLanahan 430 Dec 16, 2022
EmailAll - a powerful Email Collect tool

EmailAll A powerful Email Collect tool 0x1 介绍 😲 EmailAll is a powerful Email Co

473 Dec 22, 2022
This Tool Is For Sending Emails From A Terminal(Termux/Kali) etc.

This is a Basic python script to send emails from a Terminal(Termux/Kali) are the only tested currently.

AnonyVox 2 Apr 04, 2022
A simple email sender

Email-Sender Un semplice Email-Sender che utilizza il modulo smtplib con aggiunta di interfaccia grafica realizzata con il modulo tkinter Per il corre

Vincenzo Caliendo 0 Jan 14, 2022
Will iterate through a list of emails on an attached csv file and email all of them a message of your choice

Email_Bot Will iterate through a list of emails on an attached csv file and email all of them a message of your choice. Before using, make sure you al

J. Brandon Walker 1 Nov 30, 2021
A simple free API that allows you to extract abuse emails from IPs.

Abuse-Email-API A simple free API that allows you to extract abuse emails from IPs. also isnt worth 500 dollars :) Requirements A Debian based OS The

Keratin 1 Dec 20, 2021
Django SMTP Protocol with Gmail

Django SMTP Protocol with Gmail This is the free service from gmail to send and receive emails. What we need for this things done, Python/pip install

Mehedi Hasan 3 Dec 13, 2022
Euserv_extend captcha solver + pin code(Gmail)

Euserv_extend captcha solver + pin code(Gmail)

19 Nov 30, 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,

Zacky2613 1 Aug 26, 2022
this is django project through this project you can easily sends message to any email

SEND-EMAIL this is django project through this project you can easily sends message to any email home when you run the server then you will see this t

Ankit jadhav 1 Oct 17, 2021
📧 CLI to deduplicate mails from mail boxes.

Mail Deduplicate Command-line tool to deduplicate mails from a set of boxes. Stable release: Development: Features Duplicate detection based on cherry

Kevin Deldycke 134 Dec 14, 2022
Disposable email validator for python

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

1 Jan 05, 2022
Collection of emails sent from the Hungarian gov and Viktor Orbán to the citizens of Hungary

Public list of Hungary and Viktor Orbán's emails since March 2021 Collection of emails sent from the Hungarian government and Viktor Orbán to the citi

Miguel Sozinho Ramalho 1 Mar 28, 2022
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

Karma Computing 0 Sep 07, 2021
ParaskinioTouristOffices - This program sends a message to various email adresses

ParaskinioTouristOffices This program sends a message to various email adresses.

Odysseas Psomaderis 2 Feb 11, 2022