Giter Site home page Giter Site logo

red-box's Introduction

Red Box: Advanced Email Box Reader

Next generation email box reader/manager


Pypi version build codecov Documentation Status PyPI pyversions

What is it?

Red Box is an advanced email box reader library. It is a sister library for Red Mail, advanced email sender. It makes managing your email box in Python very easy.

Core features:

  • Easy email searching
  • Intuitive message manipulation
  • Intuitive email box manipulation

Install it from PyPI:

pip install redbox

Why Red Box?

Imaplib from standard library is complex to use and unintuitive. Red Box makes reading email boxes easy.

With Red Box, it is simple as this:

from redbox import EmailBox

# Create an email box instance
box = EmailBox(host="localhost", port=0)

# Select an email folder
inbox = box['INBOX']

# Get emails
emails = inbox.search(
    from_="[email protected]",
    subject="Red Box released",
    unseen=True
)

More Examples

There is also a query language for arbitrary search queries:

from redbox.query import FROM, UNSEEN, FLAGGED

emails = inbox.search(
    FROM('[email protected]') & (UNSEEN | FLAGGED)
)

Red Box also makes reading different parts of the email messages easy:

# Get one email
email = emails[0]

# String representation of the message
print(email.content)

# Email contents
print(email.text_body)
print(email.html_body)

# Email headers
print(email.from_)
print(email.to)
print(email.date)

Here is a complete example:

from redbox import EmailBox

box = EmailBox(host="localhost", port=0)
inbox = box['INBOX']

for msg in inbox.search(subject="example 2", unseen=True):

    # Process the message
    print(msg.subject)
    print(msg.text_body)

    # Set the message as read/seen
    msg.read()

See more from the documentation.

If the library helped you save time, consider buying a coffee for the maintainer โ˜•.

Author

red-box's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

red-box's Issues

Not connecting to iCloud IMAP mailbox

Hello, unfortunately I'm having issues connecting to an iCloud IMAP mailbox

from redbox import EmailBox
from pprint import pprint
import os
import dotenv

dotenv.load_dotenv()

imap_host = os.getenv('imap_host')
imap_user = os.getenv('imap_user')
imap_pass = os.getenv('imap_pass')

box = EmailBox(
    host=imap_host,
    port=993,
    username=imap_user,
    password=imap_pass
)

inbox = box["INBOX"]

for msg in inbox.search(subject='Your Backup Summary'):
    pprint(msg.from_)
    pprint(msg.to)
    pprint(msg.subject)
    pprint(msg.text_body)
    pprint(msg.html_body)

Error message:

Traceback (most recent call last):
  File "/Users/[Redacted]/check_for_code.py", line 19, in <module>
    inbox = box["INBOX"]
  File "/Users/[Redacted]/venv/lib/python3.9/site-packages/redbox/box.py", line 37, in __getitem__
    for mailbox in self.mailfolders:
  File "/Users/[Redacted]/venv/lib/python3.9/site-packages/redbox/box.py", line 45, in mailfolders
    self.update()
  File "/Users/[Redacted]/venv/lib/python3.9/site-packages/redbox/box.py", line 83, in update
    items = match.groupdict()
AttributeError: 'NoneType' object has no attribute 'groupdict'

I tried some debugging, but can't see any obvious issue beyond '_connection': None

pprint(box.__dict__)

Output:

{'_EmailBox__password': [Redacted],
 '_connection': None,
 '_mailfolders': None,
 'cls_imap': <class 'imaplib.IMAP4_SSL'>,
 'host': 'imap.mail.me.com',
 'kws_imap': {},
 'port': 993,
 'use_starttls': False,
 'username': [Redacted]}

Other notes

  • I tried setting use_starttls=True but this didn't resolve

Obtaining Email Message HTML body error

Hi there, I get the following error when attempting to get an html email via redbox.

Traceback (most recent call last): File "/Users/max/support-bot/sandbox.py", line 45, in <module> test2() File "/Users/max/support-bot/sandbox.py", line 43, in test2 print(emails[0].html_body) File "/Users/max/.local/share/virtualenvs/support-bot-ZEAB9n9N/lib/python3.10/site-packages/redbox/models/message.py", line 48, in html_body return insp.get_html_body() File "/Users/max/.local/share/virtualenvs/support-bot-ZEAB9n9N/lib/python3.10/site-packages/redbox/utils/inspector.py", line 15, in get_html_body content_type = pl['Content-Type'].split(";") TypeError: string indices must be integers

Any insight would be great.

Gmail MailFolders with spaces in their name don't work

Expected Behavior

Searching Gmail MailFolders with spaces in their names should work the same as MailFolders without spaces.

Actual Behavior

Searching Gmail MailFolders with spaces in their names throws imaplib.error: SELECT command error: BAD [b'Could not parse command'].

  File "/Users/Username/Library/Python/3.9/lib/python/site-packages/redbox/models/mailbox.py", line 51, in search
    self.select()
  File "/Users/Username/Library/Python/3.9/lib/python/site-packages/redbox/models/mailbox.py", line 26, in select
    self.session.select(self.name, readonly=self.readonly)
  File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/imaplib.py", line 756, in select
    typ, dat = self._simple_command(name, mailbox)
  File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/imaplib.py", line 1230, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/imaplib.py", line 1055, in _command_complete
    raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.error: SELECT command error: BAD [b'Could not parse command']

Steps to Reproduce the Problem

  1. Run the program below, replacing [email protected] with a real email address, and asdf asdf asdf asdf with a real password
from redbox import gmail

# Set credentials
gmail.username = "[email protected]"
gmail.password = "asdf asdf asdf asdf"
folder = gmail["[Gmail]/All Mail"]
#                       ^^^^^^^^
# Notice the space in folder name

# Search folders
for msg in folder.search(unseen=False):
    print(msg.subject)
    print(msg.text_body)

Note: Running the same program with a MailFolder with no spaces, like [Gmail]/Important, works.

Specifications

  • RedBox: 0.2.1
  • Python: 3.9.6
  • Platform: macOS 13.0

Obtaining Mailfolders error

I'm trying to connect on a private IMAP server.

# initiate the connection
self.imap_connection=EmailBox(self.config.imap_host, self.config.imap_port,self.config.imap_username,self.config.imap_password)
# then i run the following code
inbox=self.imap_connection.mailfolders # this line throws error
print(inbox)

Error obtained
AttributeError: 'NoneType' object has no attribute 'groupdict'. Did you mean: '_mailfolders'?

supporting parse simple chinese in Class Message[Read, Content]

def get_unread_mail():
    box = EmailBox(
        host="imap.gmail.com",
        port="993",
        username="",
        password="",
    )
    msgs = box["INBOX"].search(unseen=True)
    # msgs [0].subject
    msg.unread()

when simple chinese text in msgs [0].subject, it return:

Subject: =?UTF-8?Q?Re:_[Bug]:?==?UTF-8?Q?_=E

Exception on date retrieval

Hey, thanks for this piece of software. Have been using in some of my scripts. However, today I run into an issue while extracting the information from one of the emails.

In [64]: msg = inbox.search(SUBJECT("XXXXX"))

In [65]: msg
Out[65]: 
[EmailMessage(session=<imaplib.IMAP4_SSL object at 0x7fdc08e69870>, uid=279, mailbox='INBOX'),
 EmailMessage(session=<imaplib.IMAP4_SSL object at 0x7fdc08e69870>, uid=280, mailbox='INBOX'),
 EmailMessage(session=<imaplib.IMAP4_SSL object at 0x7fdc08e69870>, uid=281, mailbox='INBOX')]

In [66]: msg[0]
Out[66]: EmailMessage(session=<imaplib.IMAP4_SSL object at 0x7fdc08e69870>, uid=279, mailbox='INBOX')

In [67]: msg[0].date
Out[67]: datetime.datetime(2024, 1, 16, 10, 57, 48, tzinfo=datetime.timezone.utc)

In [68]: msg[1].date
Out[68]: datetime.datetime(2023, 12, 19, 16, 27, 9, tzinfo=datetime.timezone.utc)

In [69]: msg[2].date
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-69-2efa661e9837> in <module>
----> 1 msg[2].date

~/.local/lib/python3.10/site-packages/redbox/models/message.py in date(self)
     82         headers = {k.lower(): v for k, v in self.headers.items()}
     83         date = headers['date']
---> 84         return datetime.datetime.strptime(date, "%a, %d %b %Y %H:%M:%S %z")
     85 
     86     def read(self):

/usr/lib/python3.10/_strptime.py in _strptime_datetime(cls, data_string, format)
    566     """Return a class cls instance based on the input string and the
    567     format string."""
--> 568     tt, fraction, gmtoff_fraction = _strptime(data_string, format)
    569     tzname, gmtoff = tt[-2:]
    570     args = tt[:6] + (fraction,)

/usr/lib/python3.10/_strptime.py in _strptime(data_string, format)
    347     found = format_regex.match(data_string)
    348     if not found:
--> 349         raise ValueError("time data %r does not match format %r" %
    350                          (data_string, format))
    351     if len(data_string) != found.end():

ValueError: time data '17 Jan 2024 21:34:20 +0000' does not match format '%a, %d %b %Y %H:%M:%S %z'

This email was automatically forwarded from one email provider to another one, not sure if that's what caused the issue. Fix seems to be an easy one, will try to PR eventually but wanted to put it here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.