diff --git a/docs/source/code/flags.rst b/docs/source/code/enums.rst similarity index 71% rename from docs/source/code/flags.rst rename to docs/source/code/enums.rst index cb72d44..95dad2d 100644 --- a/docs/source/code/flags.rst +++ b/docs/source/code/enums.rst @@ -1,7 +1,7 @@ Flag Module ============= -.. automodule:: sage_imap.helpers.flags +.. automodule:: sage_imap.helpers.enums :members: :undoc-members: :show-inheritance: diff --git a/docs/source/code/message.rst b/docs/source/code/models.rst similarity index 71% rename from docs/source/code/message.rst rename to docs/source/code/models.rst index 5a337da..54a04b7 100644 --- a/docs/source/code/message.rst +++ b/docs/source/code/models.rst @@ -1,7 +1,7 @@ Message Module ============== -.. automodule:: sage_imap.helpers.message +.. automodule:: sage_imap.models :members: :undoc-members: :show-inheritance: diff --git a/docs/source/code/modules.rst b/docs/source/code/modules.rst index fe8a7cb..8ce7d08 100644 --- a/docs/source/code/modules.rst +++ b/docs/source/code/modules.rst @@ -6,8 +6,8 @@ Code API client exceptions - flags + enums folder mailbox - message + models search diff --git a/docs/source/getting_started/configuration.rst b/docs/source/getting_started/configuration.rst deleted file mode 100644 index f95edd1..0000000 --- a/docs/source/getting_started/configuration.rst +++ /dev/null @@ -1,13 +0,0 @@ -Configuration Guide -=================== - -Configuration -------------- - -In the configuration, you need to specify variables for both IMAP and SMTP connections to establish and manage email communication effectively. - -This library offers flexibility to accommodate both single-user and multi-user scenarios: - -- **Single User Configuration**: If you are integrating this library into a Django application or any other single-user setup, you can define the necessary variables within your application's settings. This approach ensures that the configuration behaves as a single user, maintaining a consistent and straightforward setup. - -- **Multi-User Configuration**: For applications requiring support for multiple users, such as a web application with various user accounts, the library allows you to dynamically change the configuration variables upon each instantiation. This flexibility ensures that each user can have their own IMAP and SMTP connection settings, enabling personalized email management and communication. diff --git a/docs/source/getting_started/examples/example3.rst b/docs/source/getting_started/examples/example3.rst index 8a6de44..ba2a2ad 100644 --- a/docs/source/getting_started/examples/example3.rst +++ b/docs/source/getting_started/examples/example3.rst @@ -20,7 +20,7 @@ To use the `IMAPMailboxService`, first, you need to create an instance of `IMAPC mailbox_service = IMAPMailboxService(client) # Now you can use the mailbox_service to manage mailboxes -Method: `select_mailbox` +Method: `select` ------------------------ This method selects the specified mailbox for subsequent operations. @@ -37,16 +37,16 @@ Selects a mailbox. try: with IMAPClient("imap.example.com", "username", "password") as client: mailbox_service = IMAPMailboxService(client) - mailbox_service.select_mailbox('INBOX') + mailbox_service.select('INBOX') print("Mailbox 'INBOX' selected.") except IMAPClientError as e: logging.critical("An error occurred: %s", e) **Explanation:** -- The `select_mailbox` method attempts to select the 'INBOX' mailbox. +- The `select` method attempts to select the 'INBOX' mailbox. - If the selection fails, it raises an `IMAPMailboxSelectionError`. -Method: `close_mailbox` +Method: `close` ----------------------- This method closes the currently selected mailbox. @@ -60,13 +60,13 @@ Closes the current mailbox. try: with IMAPClient("imap.example.com", "username", "password") as client: mailbox_service = IMAPMailboxService(client) - mailbox_service.close_mailbox() + mailbox_service.close() print("Mailbox closed.") except IMAPClientError as e: logging.critical("An error occurred: %s", e) **Explanation:** -- The `close_mailbox` method ensures that the currently selected mailbox is closed properly. +- The `close` method ensures that the currently selected mailbox is closed properly. - If the closure fails, it raises an `IMAPMailboxClosureError`. Method: `check` @@ -121,7 +121,7 @@ Searches for emails. - The `search` method searches for emails based on the provided criteria. - If the search operation fails, it raises an `IMAPSearchError`. -Method: `delete_temporarily` +Method: `trash` ---------------------------- This method marks messages for deletion and moves them to the trash folder. @@ -138,16 +138,16 @@ Marks messages for deletion and moves to trash. try: with IMAPClient("imap.example.com", "username", "password") as client: mailbox_service = IMAPMailboxService(client) - mailbox_service.delete_temporarily(MessageSet('1,2,3')) + mailbox_service.trash(MessageSet('1,2,3')) print("Messages marked for deletion and moved to trash.") except IMAPClientError as e: logging.critical("An error occurred: %s", e) **Explanation:** -- The `delete_temporarily` method marks the specified messages for deletion and moves them to the trash folder. +- The `trash` method marks the specified messages for deletion and moves them to the trash folder. - If the deletion or move operation fails, it raises an `IMAPMailboxDeleteError`. -Method: `delete_permanently` +Method: `delete` ---------------------------- This method permanently deletes messages marked for deletion. @@ -164,16 +164,16 @@ Permanently deletes messages. try: with IMAPClient("imap.example.com", "username", "password") as client: mailbox_service = IMAPMailboxService(client) - mailbox_service.delete_permanently(MessageSet('1,2,3')) + mailbox_service.delete(MessageSet('1,2,3')) print("Messages permanently deleted.") except IMAPClientError as e: logging.critical("An error occurred: %s", e) **Explanation:** -- The `delete_permanently` method permanently deletes the specified messages from the mailbox. +- The `delete` method permanently deletes the specified messages from the mailbox. - If the permanent deletion operation fails, it raises an `IMAPMailboxPermanentDeleteError`. -Method: `move_to_folder` +Method: `move` ------------------------ This method moves messages to the specified folder. @@ -191,16 +191,16 @@ Moves messages to a folder. try: with IMAPClient("imap.example.com", "username", "password") as client: mailbox_service = IMAPMailboxService(client) - mailbox_service.move_to_folder(MessageSet('1,2,3'), 'Archive') + mailbox_service.move(MessageSet('1,2,3'), 'Archive') print("Messages moved to 'Archive'.") except IMAPClientError as e: logging.critical("An error occurred: %s", e) **Explanation:** -- The `move_to_folder` method moves the specified messages to the given folder. +- The `move` method moves the specified messages to the given folder. - If the move operation fails, it raises an `IMAPMailboxMoveError`. -Method: `restore_from_trash` +Method: `restore` ---------------------------- This method restores messages from the trash to the original folder. @@ -218,13 +218,13 @@ Restores messages from trash. try: with IMAPClient("imap.example.com", "username", "password") as client: mailbox_service = IMAPMailboxService(client) - mailbox_service.restore_from_trash(MessageSet('1,2,3'), 'INBOX') + mailbox_service.restore(MessageSet('1,2,3'), 'INBOX') print("Messages restored to 'INBOX'.") except IMAPClientError as e: logging.critical("An error occurred: %s", e) **Explanation:** -- The `restore_from_trash` method restores the specified messages from the trash to the original folder. +- The `restore` method restores the specified messages from the trash to the original folder. - If the restore operation fails, it raises an `IMAPMailboxMoveError`. Method: `fetch` @@ -236,7 +236,7 @@ Fetches parts of messages. **Parameters:** - `msg_set` (MessageSet): The set of message IDs to be fetched. -- `message_part` (MessageParts): The part of the message to fetch (e.g., BODY, FLAGS). +- `message_part` (MessagePart): The part of the message to fetch (e.g., BODY, FLAGS). **Returns:** - `EmailIterator`: An iterator over the fetched email messages. @@ -257,7 +257,7 @@ Fetches parts of messages. - The `fetch` method retrieves specified parts of the given messages. - If the fetch operation fails, it raises an exception. -Method: `save_sent_email` +Method: `save_sent` ------------------------- This method saves a sent email to the specified folder. @@ -276,16 +276,16 @@ Saves a sent email. with IMAPClient("imap.example.com", "username", "password") as client: mailbox_service = IMAPMailboxService(client) raw_email_bytes = b"raw email content here" - mailbox_service.save_sent_email(raw_email_bytes) + mailbox_service.save_sent(raw_email_bytes) print("Sent email saved to 'SENT'.") except IMAPClientError as e: logging.critical("An error occurred: %s", e) **Explanation:** -- The `save_sent_email` method saves the raw sent email data to the specified sent folder. +- The `save_sent` method saves the raw sent email data to the specified sent folder. - If the save operation fails, it raises an `IMAPMailboxSaveSentError`. -Method: `get_mailbox_status` +Method: `status` ---------------------------- This method retrieves the status of the specified mailbox. @@ -306,13 +306,13 @@ Gets mailbox status. try: with IMAPClient("imap.example.com", "username", "password") as client: mailbox_service = IMAPMailboxService(client) - status = mailbox_service.get_mailbox_status('INBOX', MailboxStatusItems.MESSAGES) + status = mailbox_service.status('INBOX', MailboxStatusItems.MESSAGES) print("Mailbox status:", status) except IMAPClientError as e: logging.critical("An error occurred: %s", e) **Explanation:** -- The `get_mailbox_status` method retrieves the status of the specified mailbox based on the provided status items. +- The `status` method retrieves the status of the specified mailbox based on the provided status items. - If the status retrieval operation fails, it raises an `IMAPMailboxStatusError`. Usage in Different Scenarios @@ -350,7 +350,7 @@ Usage in Different Scenarios try: with IMAPClient("imap.example.com", "username", "password") as client: mailbox_service = IMAPMailboxService(client) - mailbox_service.move_to_folder(MessageSet('1,2,3'), 'Archive') + mailbox_service.move(MessageSet('1,2,3'), 'Archive') print("Emails moved to 'Archive'.") except IMAPClientError as e: logging.critical("An error occurred: %s", e) @@ -362,7 +362,7 @@ Usage in Different Scenarios try: with IMAPClient("imap.example.com", "username", "password") as client: mailbox_service = IMAPMailboxService(client) - mailbox_service.restore_from_trash(MessageSet('1,2,3'), 'INBOX') + mailbox_service.restore(MessageSet('1,2,3'), 'INBOX') print("Emails restored to 'INBOX'.") except IMAPClientError as e: logging.critical("An error occurred: %s", e) diff --git a/docs/source/getting_started/features.rst b/docs/source/getting_started/features.rst index 7aa9027..ddb86c7 100644 --- a/docs/source/getting_started/features.rst +++ b/docs/source/getting_started/features.rst @@ -27,11 +27,14 @@ Example with Context Manager: .. code-block:: python + from sage_imap.services import IMAPClient, IMAPMailboxService + try: with IMAPClient(host, username, password) as client: print(client.capabilities) with IMAPMailboxService(client) as mailbox: - pass + mailbox_service.select('INBOX') + emails = mailbox_service.fetch(MessageSet('1,2,3'), MessageParts.BODY) except IMAPClientError as e: logging.critical("An error occurred: %s", e) @@ -39,14 +42,31 @@ Example without Context Manager: .. code-block:: python + from sage_imap.services import IMAPClient, IMAPMailboxService + try: - with IMAPClient(host, username, password) as client: - mailbox_service = IMAPMailboxService(client) - mailbox_service.select_mailbox('INBOX') + client = IMAPClient(host, username, password) + mailbox_service = IMAPMailboxService(client) + + try: + mailbox_service.select('INBOX') emails = mailbox_service.fetch(MessageSet('1,2,3'), MessageParts.BODY) - mailbox_service.close_mailbox() + except IMAPClientError as e: + logging.critical("An error occurred during mailbox operations: %s", e) + finally: + try: + mailbox_service.close() + except Exception as e: + logging.warning("Failed to close the mailbox service: %s", e) + except IMAPClientError as e: logging.critical("An error occurred: %s", e) + finally: + try: + client.logout() + except Exception as e: + logging.warning("Failed to close the connection: %s", e) + Search Features with AND and OR Criteria ---------------------------------------- @@ -57,6 +77,8 @@ Example of AND Criteria: .. code-block:: python + from sage_imap.helpers.search import IMAPSearchCriteria + criteria = IMAPSearchCriteria.and_criteria( IMAPSearchCriteria.from_address("example@example.com"), IMAPSearchCriteria.subject("Meeting"), @@ -68,6 +90,8 @@ Example of OR Criteria: .. code-block:: python + from sage_imap.helpers.search import IMAPSearchCriteria + criteria = IMAPSearchCriteria.or_criteria( IMAPSearchCriteria.seen(), IMAPSearchCriteria.unseen() @@ -83,7 +107,10 @@ Example of Fetching Message Parts: .. code-block:: python - emails = mailbox_service.fetch(MessageSet('1,2,3'), MessageParts.BODY) + from sage_imap.helpers.enums import MessagePart + from sage_imap.models import MessageSet + + emails = mailbox_service.fetch(MessageSet('1,2,3'), MessagePart.BODY) for email in emails: print(email.body) @@ -106,7 +133,7 @@ Creating a `MessageSet` with a single message ID. .. code-block:: python - from sage_imap.helpers.message import MessageSet + from sage_imap.models import MessageSet # Single message ID message_set = MessageSet(msg_ids="123") @@ -120,7 +147,7 @@ Creating a `MessageSet` with a comma-separated list of message IDs. .. code-block:: python - from sage_imap.helpers.message import MessageSet + from sage_imap.models import MessageSet # Comma-separated message IDs message_set = MessageSet(msg_ids="123,124,125") @@ -134,7 +161,7 @@ Creating a `MessageSet` with a range of message IDs. .. code-block:: python - from sage_imap.helpers.message import MessageSet + from sage_imap.models import MessageSet # Range of message IDs message_set = MessageSet(msg_ids="123:125") @@ -148,7 +175,7 @@ Creating a `MessageSet` with a list of message IDs. .. code-block:: python - from sage_imap.helpers.message import MessageSet + from sage_imap.models import MessageSet # List of message IDs message_set = MessageSet(msg_ids=[123, 124, 125]) @@ -162,7 +189,7 @@ Handling an invalid message ID. .. code-block:: python - from sage_imap.helpers.message import MessageSet + from sage_imap.models import MessageSet try: # Invalid message ID @@ -178,7 +205,7 @@ Handling an empty message ID. .. code-block:: python - from sage_imap.helpers.message import MessageSet + from sage_imap.models import MessageSet try: # Empty message ID diff --git a/docs/source/getting_started/headers.rst b/docs/source/getting_started/headers.rst new file mode 100644 index 0000000..d72fb28 --- /dev/null +++ b/docs/source/getting_started/headers.rst @@ -0,0 +1,124 @@ +Email Headers +===================================================== + +Email headers contain essential information that helps in the identification, routing, and management of email messages. Below are some of the most important email headers along with explanations of their significance: + +1. **From** + + - **Description:** Specifies the email address of the sender. + + - **Importance:** It identifies the origin of the email and helps recipients know who sent the message. This header is crucial for replying to the email. + +2. **To** + + - **Description:** Specifies the primary recipient(s) of the email. + + - **Importance:** Indicates the intended recipient(s) of the message. It is used for delivering the email to the correct addresses. + +3. **Cc (Carbon Copy)** + + - **Description:** Specifies additional recipients who will receive a copy of the email. + + - **Importance:** Used to keep other parties informed. Recipients listed in the Cc field can see who else received the email. + +4. **Bcc (Blind Carbon Copy)** + + - **Description:** Specifies recipients who will receive a copy of the email without other recipients knowing. + + - **Importance:** Used for privacy when sending the same email to multiple recipients without revealing their addresses to each other. + +5. **Subject** + + - **Description:** A brief summary of the email content. + + - **Importance:** Helps recipients quickly understand the purpose of the email. It also influences whether the email gets opened and read. + +6. **Date** + + - **Description:** The date and time when the email was sent. + + - **Importance:** Provides a timestamp for the email, which is essential for organizing and managing emails chronologically. + +7. **Message-ID** + + - **Description:** A unique identifier for the email message. + + - **Importance:** Used to track and reference the email. It is crucial for threading emails and identifying duplicate messages. + +8. **Reply-To** + + - **Description:** Specifies the email address where replies should be sent, which can be different from the From address. + + - **Importance:** Directs responses to a different address, which is useful for managing replies to a specific email address or team. + +9. **In-Reply-To** + + - **Description:** References the Message-ID of the email being replied to. + + - **Importance:** Helps in organizing email threads by linking responses to the original email, enabling conversation tracking. + +10. **References** + + - **Description:** Contains the Message-IDs of related emails, usually previous messages in the thread. + + - **Importance:** Maintains the context of the conversation, making it easier to follow email threads. + +11. **Return-Path** + + - **Description:** The email address that bounces and error messages are sent to. + + - **Importance:** Used by mail servers to handle undeliverable messages and notify the sender about delivery issues. + +12. **Received** + + - **Description:** Contains information about the email servers that handled the message, including timestamps and IP addresses. + + - **Importance:** Provides a trace of the email's path from sender to recipient. This is crucial for troubleshooting delivery issues and verifying the authenticity of the email. + +13. **MIME-Version** + + - **Description:** Indicates the version of the MIME protocol used. + + - **Importance:** Ensures that the email client can correctly interpret the format of the email, especially for emails with attachments and different content types. + +14. **Content-Type** + + - **Description:** Specifies the media type and format of the email content. + + - **Importance:** Informs the email client how to process and display the email, particularly for emails containing HTML, attachments, or multiple parts. + +15. **DKIM-Signature** + + - **Description:** Contains the DKIM signature for verifying the email's authenticity. + + - **Importance:** Helps in validating that the email was indeed sent by the claimed domain and that the message has not been altered, aiding in the fight against email spoofing and phishing. + + +Importance of Email Headers +--------------------------- + +Email headers play a critical role in various aspects of email communication, including: + +1. **Identification and Verification:** + + - Headers like `From`, `Message-ID`, `DKIM-Signature`, and `Received` are essential for verifying the authenticity of an email and tracing its origin. + +2. **Routing and Delivery:** + + - Headers such as `To`, `Cc`, `Bcc`, and `Return-Path` ensure the correct delivery and routing of the email to the intended recipients. + +3. **Organization and Management:** + + - Headers like `Date`, `Subject`, `In-Reply-To`, and `References` help in organizing emails into threads and managing them chronologically. + +4. **Interoperability:** + + - Headers such as `MIME-Version` and `Content-Type` ensure that emails are correctly interpreted and displayed by different email clients, regardless of the email's content format. + +5. **Troubleshooting:** + + - The `Received` header is particularly useful for diagnosing delivery issues and understanding the path taken by the email from sender to recipient. + +6. **Security:** + + - Headers like `DKIM-Signature` and `Return-Path` play a crucial role in enhancing email security by helping to detect and prevent email spoofing and phishing attacks. diff --git a/docs/source/getting_started/index.rst b/docs/source/getting_started/index.rst index db0b549..186d1fe 100644 --- a/docs/source/getting_started/index.rst +++ b/docs/source/getting_started/index.rst @@ -8,7 +8,11 @@ Getting Started :caption: Getting Started introduction + what_is_imap installation - configuration + terminologies + search + message_set + headers features examples/index diff --git a/docs/source/getting_started/introduction.rst b/docs/source/getting_started/introduction.rst index 8cfa3c1..0868d23 100644 --- a/docs/source/getting_started/introduction.rst +++ b/docs/source/getting_started/introduction.rst @@ -1,7 +1,23 @@ Introduction -============ +======================== +An IMAP package has been developed to simplify interactions with Python's imaplib. The complex syntax has been transformed into a more user-friendly one to enhance development speed. All best practices have been meticulously followed. -Introducing the **"python-sage-imap"** package, a comprehensive tool designed to simplify the management of **IMAP email operations**. This package provides a robust set of features including **context management** for IMAP connections, handling **IMAP flags**, managing folders, **searching emails with complex criteria**, and **parsing and handling email messages**. It ensures efficient resource management and error handling through its context manager, making it easy to open and close connections seamlessly. With the ability to parse and handle email messages, this package caters to a wide range of email management needs. +This package is intended for users who require direct interaction with IMAP. Frameworks can also utilize it to create a client using Python effortlessly. -The **"python-sage-imap"** package stands out with its advanced **mailbox control capabilities**, allowing users to perform various operations such as selecting, closing, checking, and restoring mailboxes. +Features +-------- + +* **Simplified Search**: + + - Various searches can be conducted effortlessly, ranging from simple to complex. Examples are provided in the documentation. + +* **Context Manager**: + + - Proper resource management is ensured, resulting in a smaller execution footprint in the source code. + +* **Powerful Email Parser**: + + - IMAP output data can be managed easily, allowing for object-oriented interaction. + +The process for developers has been streamlined, making it easier and faster to implement IMAP functionalities while maintaining clean and efficient code. diff --git a/docs/source/getting_started/message_set.rst b/docs/source/getting_started/message_set.rst new file mode 100644 index 0000000..8646c30 --- /dev/null +++ b/docs/source/getting_started/message_set.rst @@ -0,0 +1,110 @@ +What is MessageSet +======================= + +Example 1: Single ID +-------------------- + +:: + + message_set = MessageSet("123") + print(message_set.msg_ids) # Output: "123" + +**Description:** A single email ID is provided. The `msg_ids` attribute stores this ID as a string. + +Example 2: Comma-Separated List of IDs +-------------------------------------- + +:: + + message_set = MessageSet("123,456,789") + print(message_set.msg_ids) # Output: "123,456,789" + +**Description:** Multiple email IDs are provided as a comma-separated string. The `msg_ids` attribute retains this format. + +Example 3: Range of IDs +----------------------- + +:: + + message_set = MessageSet("100:200") + print(message_set.msg_ids) # Output: "100:200" + +**Description:** A range of email IDs is provided. The `msg_ids` attribute stores this range in the same format. + +Example 4: List of IDs +---------------------- + +:: + + message_set = MessageSet([123, 456, 789]) + print(message_set.msg_ids) # Output: "123,456,789" + +**Description:** A list of email IDs is provided. The `msg_ids` attribute converts the list to a comma-separated string. + +Example 5: Mixed Format with Validations +---------------------------------------- + +:: + + message_set = MessageSet("123,200:300,400") + print(message_set.msg_ids) # Output: "123,200:300,400" + +**Description:** A mix of individual IDs and ranges is provided. The `msg_ids` attribute stores these in a comma-separated string format. + +Example 6: Valid Range with Wildcard +------------------------------------ + +:: + + message_set = MessageSet("1:*") + print(message_set.msg_ids) # Output: "1:*" + +**Description:** A range from the first message to the last message using a wildcard. The `msg_ids` attribute retains this format. + +Example 7: Invalid Range (Raises Error) +--------------------------------------- + +:: + + try: + message_set = MessageSet("300:200") + except ValueError as e: + print(e) # Output: "Invalid range in message IDs: 300:200" + +**Description:** An invalid range where the start ID is greater than the end ID. This raises a `ValueError`. + +Example 8: Invalid Message ID (Raises Error) +-------------------------------------------- + +:: + + try: + message_set = MessageSet("abc") + except ValueError as e: + print(e) # Output: "Invalid message ID: abc" + +**Description:** An invalid message ID that is not numeric. This raises a `ValueError`. + +Example 9: Empty Message IDs (Raises Error) +------------------------------------------- + +:: + + try: + message_set = MessageSet("") + except ValueError as e: + print(e) # Output: "Message IDs cannot be empty" + +**Description:** An empty string is provided for message IDs. This raises a `ValueError`. + +Example 10: Invalid Data Type (Raises Error) +-------------------------------------------- + +:: + + try: + message_set = MessageSet(123) + except TypeError as e: + print(e) # Output: "msg_ids should be a string" + +**Description:** An invalid data type (integer) is provided for message IDs. This raises a `TypeError`. \ No newline at end of file diff --git a/docs/source/getting_started/search.rst b/docs/source/getting_started/search.rst new file mode 100644 index 0000000..a393ee2 --- /dev/null +++ b/docs/source/getting_started/search.rst @@ -0,0 +1,243 @@ +IMAP Search Criteria +==================== + +The `IMAPSearchCriteria` class provides a comprehensive set of static methods and enum values to construct search criteria for querying emails from an IMAP server. Here’s a detailed explanation of each variation, categorized into single commands and complex commands. + +Single Commands +--------------- + +These are simple search criteria that can be used independently to query emails. + +1. **Basic Criteria**: + + - `ALL`: Selects all messages in the mailbox. + + :: + + IMAPSearchCriteria.ALL # Output: "ALL" + + - `SEEN`: Selects messages that have been read. + + :: + + IMAPSearchCriteria.SEEN # Output: "SEEN" + + - `UNSEEN`: Selects messages that have not been read. + + :: + + IMAPSearchCriteria.UNSEEN # Output: "UNSEEN" + + - `FLAGGED`: Selects messages that are marked. + + :: + + IMAPSearchCriteria.FLAGGED # Output: "FLAGGED" + + - `UNFLAGGED`: Selects messages that are not marked. + + :: + + IMAPSearchCriteria.UNFLAGGED # Output: "UNFLAGGED" + + - `ANSWERED`: Selects messages that have been replied to. + + :: + + IMAPSearchCriteria.ANSWERED # Output: "ANSWERED" + + - `UNANSWERED`: Selects messages that have not been replied to. + + :: + + IMAPSearchCriteria.UNANSWERED # Output: "UNANSWERED" + + - `DELETED`: Selects messages that are marked for deletion. + + :: + + IMAPSearchCriteria.DELETED # Output: "DELETED" + + - `UNDELETED`: Selects messages that are not marked for deletion. + + :: + + IMAPSearchCriteria.UNDELETED # Output: "UNDELETED" + + - `DRAFT`: Selects messages that are drafts. + + :: + + IMAPSearchCriteria.DRAFT # Output: "DRAFT" + +2. **Date-Based Criteria**: + + - `before(date: str)`: Selects messages before the specified date. + + :: + + IMAPSearchCriteria.before("01-Jan-2023") # Output: "BEFORE 01-Jan-2023" + + - `on(date: str)`: Selects messages on the specified date. + + :: + + IMAPSearchCriteria.on("01-Jan-2023") # Output: "ON 01-Jan-2023" + + - `since(date: str)`: Selects messages since the specified date. + + :: + + IMAPSearchCriteria.since("01-Jan-2023") # Output: "SINCE 01-Jan-2023" + +3. **Address-Based Criteria**: + + - `from_address(email: str)`: Selects messages from the specified email address. + + :: + + IMAPSearchCriteria.from_address("example@example.com") # Output: 'FROM "example@example.com"' + + - `to_address(email: str)`: Selects messages to the specified email address. + + :: + + IMAPSearchCriteria.to_address("example@example.com") # Output: 'TO "example@example.com"' + +4. **Content-Based Criteria**: + + - `subject(subject: str)`: Selects messages with the specified subject. + + :: + + IMAPSearchCriteria.subject("Meeting") # Output: 'SUBJECT "Meeting"' + + - `body(text: str)`: Selects messages with the specified body text. + + :: + + IMAPSearchCriteria.body("Project update") # Output: 'BODY "Project update"' + + - `text(text: str)`: Selects messages with the specified text anywhere in the email. + + :: + + IMAPSearchCriteria.text("Important") # Output: 'TEXT "Important"' + +5. **Header-Based Criteria**: + + - `header(field: str, value: str)`: Selects messages with the specified header field and value. + + :: + + IMAPSearchCriteria.header("X-Priority", "1") # Output: 'HEADER "X-Priority" "1"' + +6. **Other Criteria**: + + - `message_id(message_id: str)`: Selects messages with the specified Message-ID. + + :: + + IMAPSearchCriteria.message_id("") # Output: 'HEADER "Message-ID" ""' + + - `uid(uid: str)`: Selects messages with the specified UID or range of UIDs. + + :: + + IMAPSearchCriteria.uid("100") # Output: "UID 100" + IMAPSearchCriteria.uid("100:200") # Output: "UID 100:200" + +Complex Commands +---------------- + +These involve combining multiple criteria using logical operations (AND, OR, NOT) to form more advanced queries. + +1. **AND Criteria**: + + - Combines multiple criteria with a logical AND. + + :: + + criteria = IMAPSearchCriteria.and_criteria( + IMAPSearchCriteria.SEEN, + IMAPSearchCriteria.from_address("example@example.com"), + IMAPSearchCriteria.subject("Meeting") + ) + # Output: (SEEN FROM "example@example.com" SUBJECT "Meeting") + + - This command ensures that all combined criteria must be met for an email to be selected. For example, it will select emails that are both seen, from a specific sender, and with a specific subject. + +2. **OR Criteria**: + + - Combines multiple criteria with a logical OR. + + :: + + criteria = IMAPSearchCriteria.or_criteria( + IMAPSearchCriteria.SEEN, + IMAPSearchCriteria.UNSEEN + ) + # Output: (OR SEEN UNSEEN) + + - This command ensures that if any of the combined criteria are met, the email will be selected. For example, it will select emails that are either seen or unseen. + +3. **NOT Criteria**: + + - Negates a criteria. + + :: + + criteria = IMAPSearchCriteria.not_criteria(IMAPSearchCriteria.SEEN) + # Output: NOT (SEEN) + + - This command selects emails that do not meet the specified criteria. For example, it will select emails that are not seen. + +4. **Recent Criteria**: + + - Selects emails within the specified number of recent days. + + :: + + criteria = IMAPSearchCriteria.recent(7) + # Output: SINCE + + - This command uses the current date and calculates the date from a specified number of days ago to select emails received within that timeframe. + +Examples +-------- + +**Simple Criteria:** + +:: + + criteria = IMAPSearchCriteria.SEEN + print(criteria) # Output: "SEEN" + + criteria = IMAPSearchCriteria.before("01-Jan-2023") + print(criteria) # Output: "BEFORE 01-Jan-2023" + + criteria = IMAPSearchCriteria.from_address("example@example.com") + print(criteria) # Output: 'FROM "example@example.com"' + +**Complex Criteria:** + +:: + + criteria = IMAPSearchCriteria.and_criteria( + IMAPSearchCriteria.SEEN, + IMAPSearchCriteria.from_address("example@example.com"), + IMAPSearchCriteria.subject("Meeting") + ) + print(criteria) # Output: (SEEN FROM "example@example.com" SUBJECT "Meeting") + + criteria = IMAPSearchCriteria.or_criteria( + IMAPSearchCriteria.SEEN, + IMAPSearchCriteria.UNSEEN + ) + print(criteria) # Output: (OR SEEN UNSEEN) + + criteria = IMAPSearchCriteria.not_criteria(IMAPSearchCriteria.SEEN) + print(criteria) # Output: NOT (SEEN) + + criteria = IMAPSearchCriteria.recent(7) + print(criteria) # Output: SINCE diff --git a/docs/source/getting_started/terminologies.rst b/docs/source/getting_started/terminologies.rst new file mode 100644 index 0000000..da6d52b --- /dev/null +++ b/docs/source/getting_started/terminologies.rst @@ -0,0 +1,115 @@ +Terminologies +======================================= + +IMAP is a standard email protocol that allows users to access and manage their email on a mail server. Here are some key terminologies related to IMAP: + +Key Terminologies +----------------- + +1. **IMAP Server**: + - The server that hosts the user's email and allows access via the IMAP protocol. It stores the emails and provides various services like fetching, reading, and organizing messages. + +2. **Client**: + - The software or application used to access email from the IMAP server. Examples include email clients like Microsoft Outlook, Mozilla Thunderbird, and mobile email apps. + +3. **Mailbox**: + - A folder or storage area on the IMAP server where email messages are kept. Common mailboxes include the Inbox, Sent, Drafts, and Trash. + +4. **Message**: + - An individual email that contains headers (like the sender, recipient, subject) and a body (the content of the email, which can be text or HTML, and attachments). + +5. **Flags**: + - Indicators that can be set on messages to mark their status. Common flags include \Seen (message has been read), \Answered (message has been replied to), \Flagged (message is marked for follow-up), \Deleted (message is marked for deletion), and \Draft (message is a draft). + +6. **Capability**: + - A feature or command supported by the IMAP server. Clients can query the server for its capabilities to understand what commands and features it supports. + +7. **Synchronization**: + - The process of ensuring that the email client and the server are in agreement regarding the status and content of messages. IMAP allows for real-time synchronization of email across multiple devices. + +8. **Expunge**: + - The command used to permanently remove messages marked for deletion from the server. Messages are usually flagged for deletion first and then expunged to free up space. + +9. **Fetch**: + - A command used to retrieve specific parts or attributes of an email message, such as headers, body, or flags. + +10. **Search**: + - A command that allows clients to search for messages based on specific criteria like sender, recipient, subject, date, and flags. + +Message-ID Header +----------------- + +**Definition:** +The Message-ID header is a unique identifier assigned to every email message. This identifier is used to distinguish each email uniquely across different mail systems and servers. + +**Format:** +The format of a Message-ID is standardized by the Internet Engineering Task Force (IETF) in RFC 5322. It typically looks like this: +``` + +``` +- `unique-string`: A unique combination of characters generated by the sending email server, which can include alphanumeric characters and sometimes special characters. +- `domain`: The domain name of the sending server. + +**Purpose:** +- **Uniqueness:** Ensures that each email has a distinct identity, preventing confusion with other messages. +- **Threading:** Email clients use the Message-ID to group related messages together (e.g., replies and forwards) to create conversation threads. +- **Tracking:** Useful for tracking the message through different servers and clients, aiding in troubleshooting and spam detection. + +UID (Unique Identifier) +----------------------- + +**Definition:** +A UID is a permanent, unique identifier assigned to each message in an IMAP mailbox. Unlike sequence numbers, UIDs do not change and remain constant even if the order of messages changes. + +**Purpose:** +- **Stability:** Provides a stable way to reference a specific message, even across different sessions and connections. +- **Synchronization:** Used by email clients to synchronize messages accurately with the server. Since UIDs are unique and unchanging, clients can track which messages have been processed. +- **Efficiency:** Allows clients to efficiently manage and retrieve specific messages without ambiguity. + +**Usage:** +- When a client requests a message by its UID, the server can quickly locate and provide the exact message, ensuring that the client receives the correct data. + +Sequence Number +--------------- + +**Definition:** +A sequence number is a temporary identifier assigned to a message based on its position in the mailbox. Sequence numbers start at 1 and increment by 1 for each message. + +**Characteristics:** + +- **Transience:** Sequence numbers are dynamic and can change if messages are added, deleted, or moved within the mailbox. + +- **Position-Based:** Reflects the message's current position in the mailbox, not its unique identity. + +**Purpose:** + +- **Ordering:** Helps in identifying the relative order of messages in a mailbox, which is useful for displaying messages in chronological order. + +- **Range Operations:** Allows clients to perform operations on a range of messages based on their sequence numbers (e.g., fetching, deleting). + +**Differences Between UID and Sequence Number:** + +- **Permanence:** UIDs are permanent and do not change, while sequence numbers can change as the mailbox is modified. + +- **Uniqueness:** UIDs are globally unique within the mailbox, ensuring consistent identification. Sequence numbers are unique only temporarily and are relative to the current mailbox state. + +Practical Example +----------------- + +Imagine an IMAP mailbox with the following messages: + +1. `UID=101, Sequence Number=1, Message-ID=` +2. `UID=102, Sequence Number=2, Message-ID=` +3. `UID=103, Sequence Number=3, Message-ID=` + +If the second message (UID=102) is deleted: + +The sequence numbers for remaining messages will change: + +- `UID=101` becomes `Sequence Number=1` +- `UID=103` becomes `Sequence Number=2` + +The UIDs remain the same: + +- `UID=101` is still `UID=101` +- `UID=103` is still `UID=103` diff --git a/docs/source/getting_started/what_is_imap.rst b/docs/source/getting_started/what_is_imap.rst new file mode 100644 index 0000000..c79589e --- /dev/null +++ b/docs/source/getting_started/what_is_imap.rst @@ -0,0 +1,86 @@ +What is IMAP +======================================= + +IMAP stands for **Internet Message Access Protocol**. It is a standard email protocol that is used to retrieve emails from a mail server. Unlike the older POP (Post Office Protocol), IMAP allows you to view your messages on multiple devices as it stores the email on the server rather than downloading it to a single device. + +Key Features of IMAP +-------------------- + +1. **Remote Email Storage**: + + - Emails are stored on the server. + - Users can view and manage their emails from multiple devices (e.g., desktop, laptop, smartphone) as all the actions are synchronized across devices. + +2. **Selective Synchronization**: + + - Users can choose to download only the headers of emails, which allows for faster synchronization. + - Full email content and attachments can be downloaded only when needed. + +3. **Folder Management**: + + - Users can create, rename, delete, and manage email folders directly on the server. + - Changes made to the folder structure are synchronized across all devices. + +4. **Status Flags**: + + - IMAP supports various flags such as read/unread, deleted, flagged, etc., which help in organizing and managing emails efficiently. + +5. **Multiple Mailboxes**: + + - Users can access multiple mailboxes on the same server. + - Useful for managing different email accounts or shared mailboxes. + +How IMAP Works +-------------- + +1. **Client-Server Communication**: + - The email client (such as Outlook, Thunderbird, or a mobile email app) communicates with the email server using the IMAP protocol over a network. + +2. **Authentication**: + - The user must authenticate with the email server using their credentials (username and password). + +3. **Fetching Emails**: + - The client requests the list of emails or specific email headers from the server. + - The server responds with the requested information. + +4. **Email Operations**: + - The client can perform various operations such as marking emails as read/unread, moving emails to different folders, deleting emails, etc. + - These operations are sent to the server, which processes them and updates its database accordingly. + +Advantages of IMAP +------------------ + +- **Synchronization**: Changes made on one device are reflected on all devices. +- **Accessibility**: Emails are stored on the server, so they can be accessed from anywhere with an internet connection. +- **Organization**: Users can organize their emails into folders, and these folders are synchronized across all devices. +- **Efficiency**: Only the necessary parts of emails can be downloaded, saving bandwidth and storage on the client device. + +IMAP vs. POP3 +------------- + +- **Storage**: IMAP stores emails on the server, while POP3 downloads emails to the client device and often deletes them from the server. +- **Accessibility**: IMAP allows access from multiple devices, whereas POP3 is typically used for a single device. +- **Synchronization**: IMAP synchronizes email status across devices, but POP3 does not. +- **Folder Management**: IMAP supports server-side folder management, while POP3 does not. + +Common IMAP Commands +-------------------- + +- **LOGIN**: Authenticate the user. +- **SELECT**: Select a mailbox to access. +- **FETCH**: Retrieve email messages or parts of messages. +- **STORE**: Update the flags of a message. +- **SEARCH**: Search the mailbox for messages matching criteria. +- **COPY**: Copy messages to another mailbox. +- **LOGOUT**: End the IMAP session. + +Ports Used by IMAP +------------------ + +- **Port 143**: Default IMAP port for non-encrypted communication. +- **Port 993**: IMAP over SSL/TLS (IMAPS), for encrypted communication. + +Conclusion +---------- + +IMAP is a powerful and flexible email protocol that enhances the user experience by providing seamless synchronization and accessibility across multiple devices. It is widely used by email clients and services due to its robust features and ability to manage email effectively on a centralized server.