Skip to content

Working With MailFolders

Daniel Collingwood edited this page May 18, 2024 · 7 revisions

Getting a MailFolder

Here are a few different ways:

  1. (any release or pre-release after version 2.10.0)
var mailFolder = await _imapReceiver.MailFolderClient.GetFolderAsync([mailFolderName], cancellationToken);
  1. (any release or pre-release after version 2.10.0)
var mailFolder = await _imapReceiver.MailFolderClient.GetOrCreateFolderAsync(mailFolderName, cancellationToken);
  1. (any release or pre-release after version 2.10.0)
var mailFolder = await _imapReceiver.ImapClient.Inbox.GetOrCreateSubfolderAsync(mailFolderName, cancellationToken);
  1. (any release or pre-release after version 2.10.0)
var mailFolder = await messageSummary.Folder.GetOrCreateSubfolderAsync(mailFolderName, cancellationToken);
  1. (version 2.10.0 or below)
public async Task<IMailFolder> GetOrCreateFolderAsync(string mailFolderName, CancellationToken cancellationToken = default)
{
    var client = _imapReceiver.ImapClient;
    var baseFolder = client.GetFolder(client.PersonalNamespaces[0]);
    folder = baseFolder.GetSubfolders(false, CancellationToken.None).FirstOrDefault(x =>
        mailFolderName.Equals(x.Name, StringComparison.OrdinalIgnoreCase));
    try
    {
        folder ??= await client.GetFolderAsync(mailFolderName, cancellationToken).ConfigureAwait(false);
    }
    catch (FolderNotFoundException)
    {
        folder = await baseFolder.CreateAsync(mailFolderName, isMessageFolder: true, cancellationToken);
    }
}
  1. (version 2.10.0 or below)
public static async Task<IMailFolder> GetOrCreateSubfolderAsync(this IMailFolder baseFolder, string mailFolderName, CancellationToken cancellationToken = default)
{
    IMailFolder mailFolder;
    try
    {
        mailFolder = await baseFolder.GetSubfolderAsync(mailFolderName, cancellationToken);
    }
    catch (FolderNotFoundException)
    {
        mailFolder = await baseFolder.CreateAsync(mailFolderName, isMessageFolder: true, cancellationToken);
    }
    return mailFolder;
}

Adding Mail To A Folder

await _imapReceiver.MailFolderClient.DraftsFolder.AppendAsync(mimeMessage);

Moving Mail Between Folders

private async Task MoveToDestinationAsync(IMessageSummary messageSummary, string destinationFolderName, CancellationToken cancellationToken = default)
{
    var destinationFolder = await _imapReceiver.MailFolderClient.GetFolderAsync([destinationFolderName], cancellationToken);
    await messageSummary.MoveToAsync(destinationFolder, cancellationToken);
}
Clone this wiki locally