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.
46 lines
1.8 KiB
C#
46 lines
1.8 KiB
C#
using DigitalData.MessagingService.Abstraction;
|
|
using DigitalData.MessagingService.Application.Common.Interfaces;
|
|
using DigitalData.MessagingService.Application.Common.Models.MailSearch;
|
|
using DigitalData.MessagingService.Application.EmailAccount.Queries;
|
|
using DigitalData.MessagingService.Domain.Exceptions;
|
|
using MediatR;
|
|
|
|
namespace DigitalData.MessagingService.Application.EmailReceiving.Queries;
|
|
|
|
/// <summary>
|
|
/// Query to fetch emails from an IMAP mailbox.
|
|
/// </summary>
|
|
public record FetchEmailsQuery : IRequest<IEnumerable<ReceivedEmailContext>>
|
|
{
|
|
/// <summary>
|
|
/// Identifies the email account to use.
|
|
/// </summary>
|
|
public required GetSenderQuery Account { get; init; }
|
|
|
|
/// <summary>
|
|
/// Mail query used to filter and limit the emails retrieved.
|
|
/// </summary>
|
|
public MailSearchFilter Mail { get; init; } = new();
|
|
}
|
|
|
|
public class FetchEmailsQueryHandler(
|
|
ISender Sender,
|
|
IImapEmailService ImapService) : IRequestHandler<FetchEmailsQuery, IEnumerable<ReceivedEmailContext>>
|
|
{
|
|
public async Task<IEnumerable<ReceivedEmailContext>> Handle(FetchEmailsQuery request, CancellationToken cancellationToken)
|
|
{
|
|
var account = await Sender.Send(request.Account, cancellationToken)
|
|
?? throw new NotFoundException(
|
|
$"No email account found for the given criteria (Id: {request.Account.Id}, Username: {request.Account.Username}).");
|
|
|
|
if (string.IsNullOrWhiteSpace(account.ImapServer))
|
|
throw new InvalidOperationException(
|
|
$"IMAP is not configured for account '{account.Username}' (Id: {account.Id}). Set ImapServer in EmailAccounts configuration.");
|
|
|
|
return await ImapService.FetchEmailsAsync(
|
|
account,
|
|
request.Mail,
|
|
cancellationToken);
|
|
}
|
|
}
|