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
Automatically Send Custom Named Certificates via Mail

Welcome to Certificate Launchpad 🚀 Automatically Send Custom Named Certificates via Email Intro After any event, sending certificates to attendees or

Dc7 16 Oct 16, 2022
利用阿里的云函数发送电子邮件

alifc_email 主要特性 利用阿里的云函数发送电子邮件 使用场景 hw中的钓鱼邮件发送,一些邮服会解析出邮件的来源ip(此来源ip并不是邮服的ip,而是从客户端发送邮件时,邮服自动带上的客户端ip),对于这些来源ip可能会做一些风控。 本项目利用云函数出口ip较多来绕过这些风控 使用方法 首

19 Dec 01, 2022
faceFarm is an active yahoo email detection script that functions to take over the facebook account using email.

faceFarm – The simple Email Detector. Email Valid Detector for Facebook (Yahoo) faceFarm is an active yahoo email detection script that functions to t

Fadjrir Herlambang 2 Jan 18, 2022
Esio_dev 3 Oct 15, 2021
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
An email sending system with random confirmation code.

email_sending An email sending system with random confirmation code. Description Confirmation emails are sent based on the list of email addresses. Ea

Larissa Queiroz 2 Mar 22, 2022
SMTP checker to check Mail Access via SMTP

SMTP checker to check Mail Access via SMTP with easy usage ! Medusa has been written and tested with Python 3.8. It should run on any OS as long as Python and all dependencies are installed.

h3x0 23 Dec 05, 2022
Python script for imap, pop3, smtp and IPv4 analyze

Python script for imap, pop3, smtp and IPv4 analyze

Vladislav Kotletkin 1 Jan 30, 2022
Send e-mails to teachers with specified school-website using Aula, anonymously

Information : This only works in Denmark! Send e-mails to teachers with specified school-website using Aula, anonymously. Find your school via the att

Binary.club 1 Jan 24, 2022
Use Django admin to manage drip campaign emails using querysets on Django's User model.

Django Drip Drip campaigns are pre-written sets of emails sent to customers or prospects over time. Django Drips lets you use the admin to manage drip

Zapier 630 Nov 16, 2022
An automation program that checks whether email addresses are real, whether they exist and whether they are a validated mail

Email Validator It is an automation program that checks whether email addresses are real, whether they exist and whether they are a validated mail. Re

Ender MIRIZ 4 Dec 22, 2021
SMTP In some vulnerable configurations, email servers can also be aggregated Use information that gives us information about the host or network Give

SMTP In some vulnerable configurations, email servers can also be aggregated Use information that gives us information about the host or network Give. The SMTP protocol supports some basic commands s

m3hr44n 1 Jan 16, 2022
GMailBomber is a form of Internet abuse which is perpetrated through the sending of massive volumes of email to a specific email address with the goal of overflowing the mailbox and overwhelming the mail server hosting the address, making it into some form of denial of service attack.

GMailBomber is a form of Internet abuse which is perpetrated through the sending of massive volumes of email to a specific email address with the goal of overflowing the mailbox and overwhelming the

Muneeb 5 Nov 13, 2022
A spammer to send mass emails to teachers. (Education Purposes only!)

Securly-Extension-Spammer A spammer to send mass emails to teachers. (Education Purposes only!) Setup Just go a securly blocked page(You can do this b

3 Jan 25, 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

OfflineIMAP 1.7k Dec 29, 2022
Email-bomber - Email bomber unlike other email bombers u don't need your gmail email id to use this

Email-bomber - Email bomber unlike other email bombers u don't need your gmail email id to use this

rfeferfefe 82 Dec 17, 2022
📧 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
Mailrise is an SMTP server that converts the emails it receives into Apprise notifications

Mailrise is an SMTP server that converts the emails it receives into Apprise notifications. The intended use case is as an email relay for a home lab or network. By accepting ordinary email, Mailrise

Ryan Young 293 Jan 07, 2023
Automated email sending application.

autoMail Automated email sending application. This application sends email to a user when added to database. Email message contains the temperature of

Bhat Owais 1 Feb 12, 2022
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