Skip to content

Working With MailFolders

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

Getting a MailFolder

Here are a few different ways:

var mailFolderClient = new MailFolderClient(_imapReceiver);
var destinationFolder = await mailFolderClient.GetFolderAsync([mailFolderName], cancellationToken);
public async Task<IMailFolder> GetOrCreateMailFolderAsync(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);
    }
}
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

Here's one way:

private async Task MoveToDestinationAsync(IMessageSummary messageSummary, string destinationFolderName, CancellationToken cancellationToken = default)
{
    IMailFolder destinationFolder;

    try
    {
        destinationFolder = await messageSummary.Folder.GetSubfolderAsync(destinationFolderName, cancellationToken);
    }
    catch (FolderNotFoundException)
    {
        destinationFolder = await messageSummary.Folder.CreateAsync(destinationFolderName, isMessageFolder: true, cancellationToken);
    }

    await messageSummary.MoveToAsync(destinationFolder, cancellationToken);
}
Clone this wiki locally