Commit Graph

35 Commits

Author SHA1 Message Date
b2857c558f Refactor: Replace EmailAccountDto with EmailAccount
Replaced the `EmailAccountDto` class with the `EmailAccount` class across the codebase to consolidate the `EmailAccount` entity into the domain layer. Updated namespaces, method signatures, property types, and test cases to reflect this change.

Moved `EmailAccount` from `DigitalData.MessagingService.Application.Common.Dto` to `DigitalData.MessagingService.Domain.Entities`. Updated XML documentation and removed redundant project file entries. Adjusted namespaces for related queries, validators, and commands to align with the new structure.

These changes improve separation of concerns and align with domain-driven design principles.
2026-08-12 15:26:15 +02:00
91581649ba Refactor namespaces and remove Abstraction project
Replaced `DigitalData.MessagingService.Abstraction` with
`DigitalData.MessagingService.Application.Common.Dto` and
`DigitalData.MessagingService.Application.Common.Dto.MailSearch`
to improve modularity and organization.

Removed the `Abstraction` project and updated all references
to use the `Application` project. Updated namespaces, `using`
directives, and dependencies across the codebase.

Refactored interfaces, commands, queries, validators, and
services to use the new DTOs. Updated RabbitMQ integration,
AutoMapper profiles, background services, and tests to align
with the new structure.

Performed general cleanup by removing redundant `using`
directives and obsolete references.
2026-08-12 15:13:15 +02:00
5e0de6d52a Refactor email services and update password handling
Updated `EmailAccountDto` to use `required` properties for .NET 7+ compatibility, removing the `PasswordEncrypted` property and simplifying password handling.

Removed `IEncryptionService` dependency from `LimilabsEmailService` and `LimilabsImapEmailService`. Updated `ConnectAndAuthenticateSmtpAsync` and `OpenAsync` methods to remove password decryption logic.

Introduced `CancellationToken` support in `LimilabsImapEmailService` methods to improve cancellation handling for IMAP operations.

Added `Entities\` folder reference in `DigitalData.MessagingService.Domain.csproj`.
2026-08-12 14:24:17 +02:00
176e6dd6c5 Refactor: Replace EmailAttachmentContext with DTO
Replaced `EmailAttachmentContext` with `EmailAttachmentDto` across the codebase to align with the updated DTO naming convention.

- Renamed `EmailAttachmentContext` to `EmailAttachmentDto`.
- Updated property types, method signatures, and return types to use `EmailAttachmentDto`.
- Modified XML documentation references to reflect the new class name.
- Updated `ReceivedEmailContext` to `ReceivedEmailDto` and adjusted related methods and properties.
- Refactored `FetchEmailsAsync` methods and handlers to use `ReceivedEmailDto`.
- Adjusted `BuildAttachmentsAsync` and attachment handling logic in `EmailController` and `LimilabsImapEmailService`.

This refactor ensures consistency and improves code clarity while maintaining functionality.
2026-08-12 14:17:24 +02:00
48796d9917 Refactor email filtering logic in LimilabsImapEmailService
Simplify email filtering by removing server-side filtering logic
and replacing it with in-process filtering after email retrieval.
Eliminate the use of `ICriterion` and `Expression` constructs,
and move all filtering conditions (e.g., `UnseenOnly`,
`SubjectContains`, `SenderContains`, etc.) into the processing
loop.

Add an `IsSeen` property to `ReceivedEmailContext` to track
email read status. Apply `filter.MaxCount` after all filtering
and processing are complete. Update `filter.WithAttachments`
logic to conditionally include attachments in results.

Improve code readability and maintainability by consolidating
filtering logic into a single location, ensuring consistent
application of all filters.
2026-08-12 13:41:35 +02:00
f6ada2ad9e Refactor LimilabsImapEmailService for clarity and efficiency
Refactored the `LimilabsImapEmailService` class to improve email fetching and processing. Consolidated logic by inlining and removing redundant private helper methods (`FetchEmailUidsAsync` and `FetchEmailByUidAsync`). Introduced structured `#region` blocks for UID fetching and email reading.

Enhanced filtering capabilities with support for unseen emails, subject, sender, recipient, body, UID ranges, and date ranges. Improved attachment handling by categorizing inline and regular attachments into `EmailAttachmentContext`. Added conditional attachment inclusion based on `filter.WithAttachments`.

Integrated caching (`Cache.GetOrCreateAsync`) to avoid redundant email fetches. Improved error handling and logging for better fault tolerance. Overall, the changes simplify the codebase, improve readability, and enhance functionality.
2026-08-12 13:01:49 +02:00
7b5596f3e5 Refactor email fetching methods in Limilabs service
Removed public methods `FetchEmailUidsAsync` and `FetchEmailByUidAsync` from `LimilabsImapEmailService` to simplify the public API.

Refactored `FetchEmailUidsAsync` into a private static helper method that operates directly on an `Imap` instance.

Removed exception handling logic specific to the removed methods. These changes aim to encapsulate email fetching functionality and streamline the service's design.
2026-08-12 12:45:52 +02:00
118612206e Refactor IMAP initialization with OpenAsync helper
Refactored IMAP object initialization and folder selection into a new `OpenAsync` helper method to reduce code duplication and improve maintainability.

- Replaced repetitive connection, authentication, and folder selection logic in multiple methods (`FetchEmailsAsync`, `FetchEmailUidsAsync`, etc.) with `OpenAsync`.
- Removed `ConnectAndAuthenticateAsync` and `SelectFolderAsync` methods, as their functionality is now encapsulated in `OpenAsync`.
- Updated `FetchEmailUidsAsync` to remove the `EmailAccountDto account` parameter, delegating connection logic to `OpenAsync`.
- Ensured all methods now use `OpenAsync` to obtain a fully prepared `Imap` instance, improving clarity and reducing error risk.
2026-08-12 12:33:52 +02:00
a446162afa Add EmailSyncWorker and enhance IMAP service with caching
Refactored `ReceivedEmailContext` to use `record` for immutability
and value-based equality. Added `SyncIntervalSeconds` to
`EmailAccountsOptions` for configuring IMAP sync intervals.

Introduced `EmailSyncWorker` as a background service for periodic
email synchronization. Registered `IMemoryCache` and integrated
caching in `LimilabsImapEmailService` to reduce redundant fetch
operations. Optimized `FetchEmailByUidAsync` to conditionally
handle attachments and improve performance.

Refactored logging and improved code readability by adopting modern
C# features like `record`, `with` expressions, and `IOptions`.
Performed general cleanup and streamlined method implementations.
2026-08-12 11:48:29 +02:00
f521683608 /s
Simplify IMAP email fetching API and refactor logic

Removed `markAsSeen` parameter from `FetchEmailsAsync` and
`FetchEmailByUidAsync` methods in `IImapEmailService` to
simplify the API. Updated `MailSearchFilter` to make `MaxCount`
nullable for greater flexibility.

Removed `markAsSeen` from `FetchEmailByUidQuery` and
`FetchEmailsQuery` records and their handlers. Deleted
`FetchEmailByUidQueryValidator` as it is no longer needed.

Refactored `LimilabsImapEmailService`:
- Introduced `FetchEmailUidsAsync` to centralize UID fetching logic.
- Simplified `FetchEmailByUidAsync` using a new helper method.
- Consolidated connection, authentication, and folder selection
  into reusable private methods.
- Removed redundant code for search criteria and flag fetching.

Removed `IsSeen` from `ReceivedEmailContext` and improved
overall code readability and maintainability by reducing
duplication and centralizing logic.
2026-08-12 10:04:48 +02:00
f3761e96d9 refactor(imap): remove connection pool, revert to per-call Imap, add batch flags fetch
- ImapConnectionPool removed (over-engineered; IMAP server allows multiple concurrent connections)
- LimilabsImapEmailService reverted to stateless per-call new Imap() pattern (same as original)
- GetFlagsByUIDAsync(List<long>) replaces per-message GetFlagsByUID — one round-trip for all flags
- markAsSeen wired through: GetMessageByUIDAsync (true) vs PeekMessageByUIDAsync (false)
- DependencyInjection: pool registration removed, service registered directly as before
2026-08-11 15:52:17 +02:00
1fb7dcf98a Add methods for fetching email UIDs and emails by UID
Added `FetchEmailUidsAsync` to `IImapEmailService` for retrieving UIDs of emails matching a filter, optimizing scenarios where only identifiers are needed. Added `FetchEmailByUidAsync` to fetch a single email by UID, with optional attachment handling.

Implemented `FetchEmailUidsAsync` in `LimilabsImapEmailService` to connect to the IMAP server, construct search criteria, retrieve UIDs, and handle sorting and result limits. Added robust error handling for authentication and other failures.

Implemented `FetchEmailByUidAsync` in `LimilabsImapEmailService` to fetch email content and flags for a specific UID, map the data to `ReceivedEmailContext`, and handle errors with logging for non-critical failures.
2026-08-11 09:42:04 +02:00
ee279c407b Remove HasAttachments filter; enhance FetchEmails response
The `MailSearchFilter` class was updated to remove the `HasAttachments` property, simplifying the filtering logic. Corresponding client-side filtering logic in `LimilabsImapEmailService` was also removed. The IMAP search query now defaults to `Expression.All` when no criteria are provided.

The `FetchEmails` method in `EmailController` was enhanced with a new optional `firstHtmlBodyOnly` parameter. This allows returning only the HTML body of the first email or a `404 Not Found` response if no emails match the criteria. These changes improve flexibility and simplify the codebase.
2026-08-10 14:22:45 +02:00
74ec00ddd3 Refactor attachment handling in email fetching
Consolidate `WithAttachments` behavior into `MailSearchFilter` to simplify the API and reduce redundancy.

- Removed `withAttachments` parameter from `FetchEmailsAsync` in `IImapEmailService`.
- Added `WithAttachments` property to `MailSearchFilter` to control attachment inclusion.
- Removed `WithAttachments` property from `FetchEmailsQuery` as it is now encapsulated in `MailSearchFilter`.
- Updated `FetchEmailsQueryHandler` to use `MailSearchFilter` for attachment handling.
- Refactored `LimilabsImapEmailService` to use `MailSearchFilter.WithAttachments` for mapping email data.

These changes improve maintainability and clarity by centralizing attachment-related options in `MailSearchFilter`.
2026-08-10 12:05:27 +02:00
763ba67d34 Add support for optional email attachments fetching
Introduced a `withAttachments` parameter to the `FetchEmailsAsync` method in `IImapEmailService` and related layers, allowing callers to include or exclude attachment data when fetching emails. Updated `FetchEmailsQuery` and `FetchEmailsQueryHandler` to propagate this parameter.

Refactored `LimilabsImapEmailService` to conditionally process attachments and inline visuals based on the `withAttachments` flag, improving performance when attachments are not required. Replaced `Flag.Unseen` with `Expression.HasFlag(Flag.Unseen)` for better criteria handling. Cleaned up attachment-processing logic for improved readability and maintainability.
2026-08-10 11:54:35 +02:00
8e2e9af451 Refactor email search with new filter models
Replaced the old `SearchFilter` with the new `MailSearchFilter` model to enable more flexible and granular email search criteria. Introduced `DateFilter`, `UidFilter`, and `MailSortOrder` to support advanced filtering options such as date ranges, UID ranges, and sorting order. Updated `IImapEmailService` and `FetchEmailsQuery` to use the new models.

Added validators (`DateFilterValidator`, `MailSearchFilterValidator`, `UidFilterValidator`) to ensure input correctness. Refactored `LimilabsImapEmailService` to dynamically construct IMAP search queries based on the new filter properties, supporting unseen messages, text filters, and client-side attachment filtering.

Improved maintainability and scalability by cleaning up redundant code and leveraging the new models and validation framework.
2026-08-07 14:52:28 +02:00
53ba40b316 Refactor IMAP email fetching to use SearchFilter
Replaced individual parameters (`folder`, `unseenOnly`, `maxCount`) in `IImapEmailService` with a consolidated `SearchFilter` object to simplify method signatures and improve maintainability.

Renamed `MailQuery` to `SearchFilter` in `FetchEmailsQuery` for better clarity. Updated `FetchEmailsQueryHandler` and `LimilabsImapEmailService` to use the new `SearchFilter` object, ensuring consistent handling of folder selection, unread message filtering, and message count limits.

Improved logging in `LimilabsImapEmailService` to reflect the updated `SearchFilter` structure.
2026-08-07 13:25:13 +02:00
52a416f6d9 Refactor FetchEmailsQuery and improve UID handling
Moved the `Folder` property from `FetchEmailsQuery` to the
`MailQuery` record to better encapsulate query parameters.
Updated `FetchEmailsQueryHandler` to use `MailQuery.Folder`
for improved modularity. Simplified UID limiting logic in
`LimilabsImapEmailService` by replacing `Take().ToList()`
with the more concise `[.. Take()]` syntax.
2026-08-07 12:51:32 +02:00
c47d78112c Add IMAP support for email fetching and marking as seen
Introduced IMAP functionality to enable fetching emails from an
IMAP server and marking messages as seen. Updated the
`EmailAccountDto` class with IMAP-related properties
(`ImapServer`, `ImapPort`, `ImapUseSsl`) for configuration.

Added `ReceivedEmailContext` to represent received emails and
created the `IImapEmailService` interface with methods
`FetchEmailsAsync` and `MarkAsSeenAsync`. Implemented the
`LimilabsImapEmailService` class using Limilabs Mail.dll for
IMAP operations, including connection handling, email fetching,
and marking messages as seen.

Added `FetchEmailsQuery` and `MarkEmailAsSeenCommand` with
handlers to encapsulate IMAP logic. Updated `EmailsController`
with new endpoints for fetching emails and marking messages as
seen. Registered `IImapEmailService` in `DependencyInjection`.

Included exception handling and logging for robust error
management during IMAP operations.
2026-08-07 11:48:12 +02:00
890c32f1c8 Add support for email attachments in messaging service
Introduced the `EmailAttachmentContext` class to represent email
attachments, with properties for file name, content, content type,
inline display behavior, and content ID. Used conditional compilation
to support both .NET Framework and .NET versions.

Updated the `EmailContext` class to include an `Attachments`
property, enabling emails to include attachments as byte arrays or
file paths.

Enhanced the `LimilabsEmailService` class to handle attachments:
- Added the `AddAttachments` method to process inline and regular
  attachments.
- Integrated attachment handling into the email-building process.
2026-08-05 16:00:55 +02:00
fa9b4973b9 Introduce RabbitMQ consumer pool for parallel processing
Enhanced RabbitMQ email processing by introducing a `SendingEmailConsumerPool` to enable the competing consumers pattern. Each consumer operates on its own channel, improving scalability and thread safety.

- Added `SendingEmailConsumerPool` to manage multiple consumers.
- Updated `DependencyInjection` to register the consumer pool.
- Refactored `SendingEmailConsumer` for better logging and error handling.
- Updated `AsyncInitWorker` to initialize the consumer pool.
- Added `ConsumerConcurrency` to RabbitMQ configuration.
- Improved error handling in `LimilabsEmailService` with detailed SMTP error messages.
2026-08-05 15:34:33 +02:00
42b30d4ac4 Refactor SendEmailAsync to use EmailContext object
Simplified the `SendEmailAsync` method in the `IEmailService`
interface to accept a single `EmailContext` object instead of
multiple parameters. Updated the `SendingEmailConsumer` and
`LimilabsEmailService` classes to align with this change.

In `LimilabsEmailService`, refactored email construction logic
to use properties from the `EmailContext` object, including
`Sender`, `Recipients`, `Subject`, `Body`, and `IsHtml`.
Updated `ConnectAndAuthenticateSmtpAsync` to use the `Sender`
property from `EmailContext`.

These changes improve code readability, reduce parameter
complexity, and ensure consistency across the email service
implementation.
2026-08-05 14:14:27 +02:00
c6e67c0f99 Refactor email handling for improved structure
Refactored `Email` and `SendingEmailEvent` to use `record` types, consolidating email-related data into the `Email` class. Updated `SendEmailCommand` to return a `Guid` and simplified mapping logic in `EmailMappingProfile`. Adjusted `SendEmailCommandHandler` to construct `SendingEmailEvent` manually.

Updated `SendingEmailConsumer`, `EmailsController`, and `EmailSender` to reflect the new structure. Removed the old `Email` implementation. Improved logging to reference the `Mail` property.

Revised tests to align with the new structure, ensuring immutability and better separation of concerns.
2026-08-05 13:59:54 +02:00
66afdefbd8 refactor: rename OutgoingEmail files to SendingEmail 2026-08-05 13:29:53 +02:00
58ad50b96b Refactor: Rename OutgoingEmail to SendingEmail
This commit renames and refactors all instances of `OutgoingEmail` to `SendingEmail` across the codebase to improve terminology consistency and align with domain language.

- Renamed classes, interfaces, and records (e.g., `OutgoingEmailPublisher` → `SendingEmailPublisher`, `OutgoingEmailEvent` → `SendingEmailEvent`).
- Updated method signatures, parameters, and return types to use `SendingEmail`.
- Adjusted dependency injection registrations to reflect the new naming.
- Updated mappings in `EmailMappingProfile` to map `SendEmailCommand` to `SendingEmailEvent`.
- Refactored `SendEmailCommand` and its handler to work with `SendingEmailEvent`.
- Updated `EmailsController` to use `SendingEmailEvent` in the `SendEmail` action.
- Refactored integration tests to test `SendingEmailPublisher` and updated test data accordingly.
- Updated log messages, error handling, and comments to reflect the new terminology.
- Revised documentation and utility methods to use `SendingEmailEvent`.

This refactor ensures consistency, improves readability, and reduces ambiguity in the codebase.
2026-08-05 13:26:21 +02:00
601fd9be5f Refactor: Consolidate Publisher.Abstraction into Abstraction
The `DigitalData.MessagingService.Publisher.Abstraction` project has been removed, and its functionality has been merged into a new project named `DigitalData.MessagingService.Abstraction`.

- Updated namespaces from `Publisher.Abstraction` to `Abstraction` across all relevant files, including DTOs, interfaces, and classes.
- Modified the solution file to remove `Publisher.Abstraction` and add `Abstraction`, updating solution configurations and nested project mappings.
- Replaced project references to `Publisher.Abstraction` with `Abstraction` in all affected project files.
- Updated tests and integration tests to reflect the namespace and project changes.
- Refactored application-level files such as `EmailMappingProfile` and `DependencyInjection.cs` to use the new namespace.

This refactor simplifies the project structure and ensures consistency across the solution.
2026-08-05 13:16:03 +02:00
0d9d15032f Refactor email handling for multiple recipients
Refactored the `Email` and `OutgoingEmailEvent` classes to replace the `Recipient` property with a `Recipients` collection, enabling support for multiple recipients. Updated all related test cases, including `EmailSenderTests`, `EmailSenderUrlOverloadTests`, and `OutgoingEmailPublisherTests`, to reflect this change.

Moved the `EmailAccountDto` class and its references from the `DigitalData.MessagingService.Application.Common.Dtos` namespace to the `DigitalData.MessagingService.Publisher.Abstraction` namespace for better code organization. Updated `using` directives across affected files.

Removed unused `using` directives and updated the `Email` class's `ToEvent` method to map the new `Recipients` property. Adjusted test assertions to validate collections instead of single recipient strings.
2026-08-05 13:11:19 +02:00
e47333cd1d Support multiple email recipients in email-sending flow
Updated the `IEmailService` interface and related components to
support multiple recipients in the `SendEmailAsync` method.

- Replaced `Recipient` with `Recipients` in `SendEmailCommand`,
  `OutgoingEmailEvent`, and `EmailsController`.
- Updated `SendEmailCommandValidator` to validate a collection
  of recipients, ensuring at least one valid email address.
- Modified `LimilabsEmailService` to handle multiple recipients
  by iterating over the collection and adding each to the email.
- Adjusted `OutgoingEmailConsumer` to process and log multiple
  recipients.
- Updated logging and response structures to reflect the changes.

These changes enable the system to handle emails with multiple
recipients while maintaining proper validation and logging.
2026-08-05 13:02:57 +02:00
740bb8c313 Refactor email account handling for dynamic resolution
Reintroduced `EmailAccountDto` with conditional compilation to support both .NET and non-.NET environments. Updated `IEmailService` to accept `EmailAccountDto` as the sender, replacing reliance on pre-configured SMTP credentials.

Added `GetSenderQuery` and its handler to dynamically resolve email accounts based on `Id` or `Username`. Introduced `GetSenderQueryValidator` for validation, ensuring proper usage of the query.

Modified `SendEmailCommand` to include sender resolution via MediatR. Updated `OutgoingEmailEvent` to include sender information and adjusted `OutgoingEmailConsumer` and `LimilabsEmailService` to use the dynamically resolved sender.

Updated `EmailMappingProfile` to ignore the `Sender` property during mapping. Replaced `Name` with `Id` in `appsettings.Secrets.json` for email accounts. Removed the old `EmailAccountDto` folder and performed general cleanup and restructuring.
2026-08-05 12:32:08 +02:00
7fa3c4888a Refactor repository namespaces for better organization
Updated the namespace in `IRepository.cs` and `Repository.cs`
from `DigitalData.MessagingService.Application.Common.Interfaces`
to `DigitalData.MessagingService.Application.Common.Interfaces.Repositories`.
This change improves code organization by grouping repository-related
interfaces and classes under a dedicated `Repositories` namespace.
Updated `using` directives accordingly to reflect the new structure.
2026-08-05 11:06:42 +02:00
e0e399f5ed Refactor LimilabsEmailService for async operations
Modernized LimilabsEmailService by replacing synchronous SMTP
operations with asynchronous counterparts (e.g., SendMessageAsync,
CloseAsync). Introduced a new SmtpExtensions class with a
CloseSafelyAsync method for safe disconnection. Removed the
DisconnectSafely method and replaced its usage with the new
extension method. Improved exception handling and removed
redundant Task.CompletedTask calls. These changes enhance
code readability, ensure safe resource cleanup, and align
with asynchronous programming practices.
2026-08-05 11:03:59 +02:00
e53fabcda2 Refactor email account configuration for multi-account support
Refactored `EmailAccountDto` to represent a single account with
immutable properties and added an `Id` field. Introduced
`EmailAccountsOptions` to manage multiple accounts and bound it
to the `EmailAccounts` configuration section.

Updated `DependencyInjection` to register `EmailAccountsOptions`
and removed the old single-account binding. Refactored
`LimilabsEmailService` to use `EmailAccountsOptions` and select
the appropriate account dynamically.

Replaced the `EmailAccount` section in `appsettings.Secrets.json`
with a new `EmailAccounts` section supporting multiple accounts.
Added a package reference for `Microsoft.Extensions.Options.
ConfigurationExtensions` to support the options pattern.
2026-08-05 10:46:43 +02:00
7f55d97352 Refactor email publisher integration
Replaced direct registration of `OutgoingEmailPublisher` with `AddMessagingServicePublisher()` to centralize publisher setup. Removed `OutgoingEmailPublisher.cs` and its dependencies, indicating a shift to a new implementation. Updated `DependencyInjection.cs` to use `DigitalData.MessagingService.Publisher` instead of the abstraction layer. Added a project reference to `DigitalData.MessagingService.Publisher` in the infrastructure project file.
2026-07-28 11:14:42 +02:00
47f4553986 Refactor project structure and update dependencies
Reorganized project structure by introducing `core` and
`infrastructure` directories:
- Moved `Application` and `Domain` projects to `core`.
- Moved `Infrastructure` project to `infrastructure`.

Updated project references in `API`, `Infrastructure`, and
`Application` projects to reflect the new directory structure.

Added a new dependency on `Publisher.Abstraction` in the
`Application` project.
2026-07-28 10:49:32 +02:00
78c82bf129 Refactor solution structure and add RabbitMQ config
Reorganized the solution structure to align with a layered architecture:
- Replaced `src` folder with `core`, `infrastructure`, and `presentation`.
- Moved projects to their respective folders.
- Added `DigitalData.MessagingService.Publisher.Abstraction` project.
- Removed `DigitalData.MessagingService.Client` project.

Updated project configurations and nesting in the solution file.

Added `appsettings.Secrets.json` with RabbitMQ and email account settings:
- RabbitMQ configuration includes hostname, port, credentials, and queue/exchange details.
- Email configuration includes SMTP server details and credentials.
2026-07-28 10:26:15 +02:00